-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTapeEquilibrium.java
More file actions
28 lines (24 loc) · 808 Bytes
/
TapeEquilibrium.java
File metadata and controls
28 lines (24 loc) · 808 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
// Tape Equilibrium = Find the minimum difference between two parts of an array
// https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/
class TapeEquilibrium {
public int solution(int[] A) {
long left = A[0];
long right = 0;
for (int i=1; i<A.length; i++){
right += A[i];
}
int minDiff = diffAbs(right, left);
for(int i=1; i<A.length-1; i++){ //other array shouldn't be empty
left += A[i];
right -= A[i];
int diff = diffAbs(left, right);
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
private int diffAbs(long a, long b){
return (int) (a > b? a-b : b-a);
}
}