-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCanBalance.java
More file actions
40 lines (30 loc) · 954 Bytes
/
CanBalance.java
File metadata and controls
40 lines (30 loc) · 954 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
35
36
37
38
39
40
/*
* Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.
canBalance([1, 1, 1, 2, 1]) → true
canBalance([2, 1, 1, 2, 1]) → false
canBalance([10, 10]) → true
*/
package array3;
public class CanBalance {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {4, 5, -2, 3, 8};
System.out.println(canBalance(nums));
}
public static boolean canBalance(int[] nums) {
int rightTotal = 0;
for(int i = 0; i < nums.length; i ++) {
rightTotal += nums[i];
}
int leftTotal = 0;
for(int j = 0; j< nums.length; j ++) {
leftTotal += nums[j];
rightTotal -= nums[j];
if(leftTotal == rightTotal) {
System.out.println(j);
return true;
}
}
return false;
}
}