-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitSum.java
More file actions
82 lines (69 loc) · 3.04 KB
/
splitSum.java
File metadata and controls
82 lines (69 loc) · 3.04 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class splitSum {
public static List<List<Integer>> splitSum(List<Integer> nums) {
int totalLeft = 0;
int totalRight = 0;
int left = 0;
int right = nums.size() - 1;
// Empty array, or single element array.
if (right < 1) {
return Arrays.asList(new ArrayList<>(), new ArrayList<>());
}
// Sum until the indexes meet in the middle.
while (right != left) {
if (totalLeft <= totalRight) {
totalLeft = totalLeft + nums.get(left);
left = left + 1;
continue;
}
// otherwise totalLeft > totalRight
totalRight = totalRight + nums.get(right);
right = right - 1;
}
// Check middle in left group.
if (totalLeft + nums.get(left) == totalRight) {
return Arrays.asList(nums.subList(0, left + 1), nums.subList(right + 1, nums.size()));
}
// Check middle in right group.
if (totalLeft == totalRight + nums.get(right)) {
return Arrays.asList(nums.subList(0, left), nums.subList(right, nums.size()));
}
return Arrays.asList(new ArrayList<>(), new ArrayList<>());
}
// Global so they aren't reallcoated on the stack each invocation.
private static final List<List<Integer>> cases = Arrays.asList(
Arrays.asList(),
Arrays.asList(100),
Arrays.asList(99, 99),
Arrays.asList(98, 1, 99),
Arrays.asList(99, 1, 98),
Arrays.asList(1, 2, 3, 0),
Arrays.asList(1, 2, 3, 5),
Arrays.asList(1, 2, 2, 1, 0),
Arrays.asList(10, 11, 12, 16, 17),
Arrays.asList(1, 1, 1, 1, 1, 1, 6),
Arrays.asList(6, 1, 1, 1, 1, 1, 1)
);
// Test cases
public static void testCases(boolean toScreen) {
for (List<Integer> c : cases) {
if (toScreen) {
System.out.println("java: " + c + " -> " + splitSum(c));
} else {
splitSum(c);
}
}
}
public static void main(String[] args) {
testCases(true);
long startTime = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
testCases(false);
}
long elapsedTime = System.nanoTime() - startTime;
double seconds = (double) elapsedTime / 1_000_000_000.0;
System.out.println("java: " + String.format("%.3f", seconds) + " seconds");
}
}