topic
Find the longest contiguous subarray whose sum is 0.
analyze
Exhaustive method: scan the array twice to find the length of all subarrays whose sum is 0, and then select the largest one. time complexity
Improvement: Given an array such as 1, 2, 3, 4, -1, -2, -4, -3, 1, 1,1,1,1, find its accumulated sum array 1,3,6, 10,9,7,3,0,1,2,3,4,5. Sequentially scan the array and record its index value index when 0 is encountered, then the length is index-0+1. If it encounters a non-zero value, then scan at the left end again to find a number that is equal to it, then the length between these two numbers is the length of the other satisfying condition. Return the longest one. time complexity
code
import java.util.Scanner;
public class Main {
public static void main(String[] args){
//int[] a = new int[]{1, 2, 3, 4, -1, -2, -4, -3, 1, 2};
//int[] a = new int[]{1, 2, 3, 4, -1, -2, -4, -3, 1, 1};
Scanner cin = new Scanner(System.in);
String s = cin.nextLine().trim();
String[] numStr = s.split(" ");
int[] num = new int[numStr.length];
for(int i = 0;i < numStr.length;i++){
num[i] = Integer.parseInt(numStr[i]);
}
int[] res = maxSubZero(num);
for(int var: res)
System.out.println(var);
cin.close();
}
public static int [] maxSubZero(int[] a){
int[] sum = new int[a.length];
int gstart = 0, gend = 0;
sum[0] = a[0];
for(int i = 1; i < a.length; i++){
sum[i] = sum[i-1] + a[i];
}
for(int i = 0; i < sum.length; i++){
int start = 0, end = 0;
for(int j = 0; j < i; j++){
if(sum[i] == 0){
end = i;
}
else if(sum[i] == sum[j]){
start = j+1;
end = i;
//System.out.println(start + " " + end);
}
if(gend - gstart < end - start){
gend = end;
gstart = start;
}
}
}
int[] res = new int[gend-gstart+1];
for(int k = gstart; k <= gend; k++){
res[k-gstart] = a[k];
}
return res;
}
}