-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathMinAvgTwoSlice.java
More file actions
45 lines (41 loc) · 1.17 KB
/
MinAvgTwoSlice.java
File metadata and controls
45 lines (41 loc) · 1.17 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
public class MinAvgTwoSlice {
public int solution(int[] A) {
if (A.length == 2) {
return 0;
}
int[] prefixSums = computePrefixSums(A);
int startIndex2 = findStartIndex(prefixSums, 2);
int startIndex3 = findStartIndex(prefixSums, 3);
int diff = sum(prefixSums, startIndex2, 2) * 3
- sum(prefixSums, startIndex3, 3) * 2;
int startIndex;
if (diff < 0) {
startIndex = startIndex2;
} else if (diff > 0) {
startIndex = startIndex3;
} else {
startIndex = Math.min(startIndex2, startIndex3);
}
return startIndex;
}
int[] computePrefixSums(int[] A) {
int[] prefixSums = new int[A.length];
for (int i = 0; i < prefixSums.length; i++) {
prefixSums[i] = (i == 0 ? 0 : prefixSums[i - 1]) + A[i];
}
return prefixSums;
}
int findStartIndex(int[] prefixSums, int length) {
int startIndex = 0;
for (int i = 0; i < prefixSums.length - length + 1; i++) {
if (sum(prefixSums, i, length) < sum(prefixSums, startIndex, length)) {
startIndex = i;
}
}
return startIndex;
}
int sum(int[] prefixSums, int startIndex, int length) {
return prefixSums[startIndex + length - 1]
- (startIndex == 0 ? 0 : prefixSums[startIndex - 1]);
}
}