-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_sum1.java
More file actions
34 lines (26 loc) · 756 Bytes
/
Copy pathArray_sum1.java
File metadata and controls
34 lines (26 loc) · 756 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Array consist of -1 and 1, Find count of all sub-arrays where sum = 0.
//Ex. [-1,1,-1,1]
//Ans : 4
//Ex. [-1,-1,1,1]
//Ans : 2 [-1,1][-1,-1,1,1]
public class Array_sum1 {
public static int CountZero(int arr[]){
int result = 0;
for(int i=0;i<arr.length;i++){
int sum = arr[i];
for(int j=i+1;j<arr.length;j++){
sum = sum+arr[j];
if(sum == 0)
result++;
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(CountZero(new int[]{-1,1,-1,1})); //4
System.out.println(CountZero(new int[]{1,-1,-1,1,-1,-1,1})); //6
System.out.println(CountZero(new int[]{1,-1})); //1
System.out.println(CountZero(new int[]{-1})); //0
}
}