Largest subarray with 0 sum

Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0.

Input:
N = 8
A[] = {15,-2,2,-8,1,7,10,23}
Output: 5
Explanation: The largest subarray with
sum 0 will be -2 2 -8 1 7.
int maxLen(int A[], int n)
{
int maxi=0; // store max length
int sum=0; //stores the contiguous sum
unordered_map<int,int>m;
for(int i=0;i<n;i++)
{
sum+=A[i];
if(sum==0) // it is the largest sub array
{
maxi=i+1;
}
else{
if(m.find(sum)!=m.end()) //if we find the same sum that means it is a sub array with zero sum
{
maxi=max(maxi,i-m[sum]);
}
else{
m[sum]=i; //else update in hash map
}
}
}
return maxi;
}
 
 

 

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!