-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinAvgTwoSlice
38 lines (28 loc) · 1 KB
/
MinAvgTwoSlice
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
//MinAvgTwoSlice
public int minAvgTwoSliceSolution(int[] A) {
int len = A.length, result = len - 1, sum = 0;
int[] prefixSums = new int[len + 1];
for (int i = 1; i <= len; ++i) {
prefixSums[i] = prefixSums[i-1] + A[i-1];
}
double min = Double.MAX_VALUE, average = 0d;
for (int P = 0, Q = 1; Q + 1 < prefixSums.length; ++P, ++Q ) {
sum = prefixSums[Q + 1] - prefixSums[P];
average = (sum)/(double) 2;
if (average < min) {
min = average;
result = P;
}
if ( Q + 2 < prefixSums.length ) {
sum = prefixSums[Q + 2] - prefixSums[P];
average = (sum)/(double) 3;
if (average < min) {
min = average;
result = P;
}
}
}
return result;
}
int[] m = {4,2,2,5,1,5,8};
System.out.println("Min Avg Two Slice : "+obj.minAvgTwoSliceSolution(m));