-
Notifications
You must be signed in to change notification settings - Fork 4
/
MaximumAverageSubarrayII.java
76 lines (59 loc) · 1.71 KB
/
MaximumAverageSubarrayII.java
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
/*
* Click `Run` to execute the snippet below!
*/
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
spend_per_day = [10,20,60,80,30,50,70,30,60] -> [60, 80, 30, 50, 70]
58.0
maximum-average subarray
constraint: length >= 3
*/
class Solution {
public static void main(String[] args) {
int[] arr = new int[]{10,20,60,80,30,50,70,30,60};
// expects 58.0
System.out.println(findMaxAvgSubarray(arr, 3));
arr = new int[]{10,20};
// expects -infinity
System.out.println(findMaxAvgSubarray(arr, 3));
arr = new int[]{10,20,30};
// expects 20
System.out.println(findMaxAvgSubarray(arr, 3));
arr = new int[]{100,20,60,80,30,50,70,30,60};
// expects 65.0
System.out.println(findMaxAvgSubarray(arr, 3));
}
public static double findMaxAvgSubarray(int[] nums, int k) {
int len = nums.length;
double max = Double.NEGATIVE_INFINITY;
int maxStart = 0;
int maxEnd = -1;
for (int i = 0; i <= len - k; i++) {
double sum = 0;
int counter = 0;
// get first k - 1 elements
while (counter < k - 1) {
sum += nums[i + counter];
counter++;
}
// go all the way to end and check every time
while (i + counter < len) {
sum += nums[i + counter];
counter++;
double newAvg = sum / counter;
if (newAvg > max) {
max = newAvg;
maxStart = i;
maxEnd = i + counter;
}
}
}
System.out.println("(start, end): " + maxStart + ", " + maxEnd);
return max;
}
}