Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e4fe961

Browse files
Is array partitioned
1 parent f9606e2 commit e4fe961

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package codechallenge.easy.array;
2+
3+
import org.junit.Test;
4+
5+
/**
6+
* Need to check the partition patter where sum of first half of array is equal
7+
* to sum of second half
8+
* input array is [3,4,2,2,2,1]
9+
* output index of parition element 2
10+
*
11+
* * input array is [3,2,2,5,1]
12+
* * output should be -1
13+
*/
14+
public class IsArrayPartitioned {
15+
16+
// Test Driven Development by Aseem Jain
17+
@Test
18+
public void test() {
19+
int[] a = {3,4,2,2,2,1};
20+
assert 2 == solution1(a);
21+
22+
int[] b = {3,2,2,5,1};
23+
assert -1 == solution1(b);
24+
25+
assert 2 == solution2(a);
26+
27+
assert -1 == solution2(b);
28+
29+
}
30+
31+
// Basic solution O(n x n)
32+
private int solution1(int[] a) {
33+
34+
int fh =0;
35+
36+
for (int i = 0; i < a.length; i++) {
37+
fh += a[i];
38+
int sh =0;
39+
for (int j = i+1; j < a.length; j++) {
40+
sh += a[j];
41+
}
42+
if(fh == sh){
43+
return i+1;
44+
}
45+
}
46+
47+
return -1;
48+
}
49+
50+
// Optimized solution O(n)
51+
private int solution2(int[] a) {
52+
53+
int sum =0;
54+
int fh =0;
55+
56+
for (int i = 0; i < a.length; i++) {
57+
sum += a[i];
58+
}
59+
60+
// to get the partition, first half
61+
for (int i = 0; i < a.length; i++) {
62+
fh += a[i];
63+
64+
if(fh == sum/2){
65+
return i+1;
66+
}
67+
}
68+
69+
return -1;
70+
}
71+
72+
73+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /