top of page

Keep Reading !

You can also checkout more topics like...

peep-101_edited.png
EXPLORE COURSES (6).png
EXPLORE COURSES (9).png
EXPLORE COURSES (7)_edited.jpg

Largest subarray with 0 sum

The task is to compute the length of the largest subarray with sum of 0.

Example 01:

Input:
N = 8
A[] = {165,-2,2,-8,1,7,100,203}
Output: 5
Detail: The largest subarray with
sum 0 will be -2 2 -8 1 7.

Your Task: returns the length of the largest subarray with 0 sum.

Time Complexity: O(N). Auxiliary Space: O(N).

Constraints: 1 <= N <= 105 -1000 <= A[i] <= 1000, for each valid i


Solution


int maxLen(int arr[], int n)
{
    int index = -1;int sum = 0;
    int maxLen = 0;HashMap<Integer, Integer> map = new HashMap<>();
    map.put(sum,index);
    while(index <n-1){
     index++;
     sum += arr[index];
     if(map.containsKey(sum)){
      int length = index - map.get(sum) ;
        if(maxLen < length){
          maxLen = length;
             }
           }else
                 {
                map.put(sum,index);
                    }
           }
            return maxLen;
        }


14 views0 comments

Recent Posts

See All

Comments


bottom of page