-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEqualSumSubArrays.java
More file actions
42 lines (36 loc) · 1.05 KB
/
EqualSumSubArrays.java
File metadata and controls
42 lines (36 loc) · 1.05 KB
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
35
36
37
38
39
40
41
42
package Array;
public class EqualSumSubArrays {
/**
* @param arr - It is the array who's total sum is to be calculated.
* @param n - It is the length of the array.
* @return - It returns the total sum of the array.
*/
static int totalSum(int[] arr, int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
/**
* @param a - It is the array under consideration
* @return - It returns if the array 'a' has any two sub-arrays whose sums are
* equal.
*/
static boolean check(int[] a) {
int n = a.length;
int prefix = 0;
int total_sum = totalSum(a, n);
for (int num : a) {
prefix += num;
int suffix = total_sum - prefix;
if (prefix == suffix)
return true;
}
return false;
}
// Time Complexity - O(n), Auxiliary Space - O(1)
public static void main(String[] args) {
int[] a = {2, 3, -1, 8, 4};
System.out.println(check(a));
}
}