-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedSum.java
More file actions
32 lines (22 loc) · 769 Bytes
/
BalancedSum.java
File metadata and controls
32 lines (22 loc) · 769 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
import java.util.List;
//balancedSum : write a function some of all the elements to the left and
// right of the index are equal , return that index.
// if no such index exists return -1
public class BalancedSum {
public static void main(String[] args) {
List<Integer> list = List.of(1, 5, 3, 4, 2);
System.out.println(balancedSum(list));
}
static int balancedSum(List<Integer> arr) {
int size = arr.size();
int rSum = arr.stream().skip(1).mapToInt(Integer::intValue).sum();
int lSum = 0;
for (int i = 0, j = 1; j < size; i++, j++) {
rSum -= arr.get(j);
lSum += arr.get(i);
if (lSum == rSum)
return i + 1;
}
return -1;
}
}