maximum subarray whose sum equals 0

后端 未结 12 1374
礼貌的吻别
礼貌的吻别 2020-12-04 08:14

An array contains both positive and negative elements, find the maximum subarray whose sum equals 0.

12条回答
  •  悲&欢浪女
    2020-12-04 09:03

    Another solution to this problem could be: 1. Calculate sum for entire array 2. Now follow following formula to get the largest subarray with sum zero:

    Math.max(find(a,l+1,r,sum-a[l]), find(a,l,r-1,sum-a[r]));
    where l=left index, r= right index, initially their value=0 and a.length-1
    

    Idea is simple, max size we can get with sum=0, is the size of array then we start skipping elements from left and right recursively, the moment we get sum=0 we stop. Below is the code for same:

    static int find(int a[]) {
        int sum =0;
        for (int i = 0; i < a.length; i++) {
            sum = sum+a[i];
        }
    
        return find(a, 0, a.length-1, sum);
    }
    
    
    static int find(int a[], int l, int r, int sum) {
        if(l==r && sum>0) {
            return 0;
        }
        if(sum==0) {
            return r-l+1;
        }
        return Math.max(find(a,l+1,r,sum-a[l]), find(a,l,r-1,sum-a[r]));
    
    }
    

提交回复
热议问题