Longest subarray zero sum
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
The following line contains N space separated integers, that denote the value of the elements of the array.
The first and only line of output contains length of the longest subarray whose sum is zero.
0 <= N <= 10^8
Time Limit: 1 sec
10
95 -97 -387 -435 -5 -70 897 127 23 284
5
The five elements that form the longest subarray that sum up to zero are: -387, -435, -5, -70, 897
#include<bits/stdc++.h>int lengthOfLongestSubsetWithZeroSum(int* arr, int n) { // Write your code hereint sum=0;int maxm=0; unordered_map<int,int>mp; //mp[0] = -1; for(int i=0;i<n;i++){ //mp[arr[i]]=sum; sum+=arr[i]; if(mp.count(sum)>0){ maxm=max(maxm,i -mp[sum]); } else { mp[sum] = i; } } return maxm;}
Comments
Post a Comment