Skip to content

Commit 7406984

Browse files
committed
Add codility exercise - 1
1 parent de7507f commit 7406984

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package codility;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class SearchEquilibrium {
9+
10+
@Test
11+
public void test() {
12+
int[] arr = new int[9];
13+
arr[0] = -4;
14+
arr[1] = 8;
15+
arr[2] = 16;
16+
arr[3] = -22;
17+
arr[4] = 0;
18+
arr[5] = -4;
19+
arr[6] = 8;
20+
arr[7] = 16;
21+
arr[8] = -22;
22+
assertThat(true, is(solution(arr) == 0 || solution(arr) == 4));
23+
}
24+
25+
public int solution(int[] arr) {
26+
if (arr == null) return -1;
27+
28+
int total = 0;
29+
for (int i = 0; i < arr.length; i++) {
30+
total += arr[i];
31+
}
32+
33+
if (total - arr[0] == 0) {
34+
return 0;
35+
}
36+
37+
int left = 0;
38+
for (int i = 1; i < arr.length; i++) {
39+
left += arr[i - 1];
40+
if ((total - arr[i])/2 == left) {
41+
return i;
42+
}
43+
}
44+
45+
return -1;
46+
}
47+
}

0 commit comments

Comments
 (0)