644 Maximum Average Subarray II

1. Question

Given an array consisting ofnintegers, find the contiguous subarray whose length is greater than or equal tokthat has the maximum average value. And you need to output the maximum average value.
Example 1:
1
Input: [1,12,-5,-6,50,3], k = 4
2
3
Output: 12.75
4
5
Explanation:
6
7
when length is 5, maximum average value is 10.8,
8
when length is 6, maximum average value is 9.16667.
9
Thus return 12.75.
Copied!
Note:
  1. 1.
    1 <=k<=n<= 10,000.
  2. 2.
    Elements of the given array will be in range [-10,000, 10,000].
  3. 3.
    The answer with the calculation error less than 10^-5 will be accepted.

2. Implementation

(1) Brute Force
1
class Solution {
2
public double findMaxAverage(int[] nums, int k) {
3
int n = nums.length;
4
double res = Integer.MIN_VALUE;
5
6
for (int i = 0; i <= n - k; i++) {
7
double sum = 0;
8
for (int j = i; j < n; j++) {
9
sum += nums[j];
10
11
if (j - i + 1 >= k) {
12
res = Math.max(res, sum * 1.0 / (j - i + 1));
13
}
14
}
15
}
16
return res;
17
}
18
}
Copied!
(2) Binary Search
1
class Solution {
2
public double findMaxAverage(int[] nums, int k) {
3
double start = Integer.MAX_VALUE;
4
double end = Integer.MIN_VALUE;
5
6
for (int num : nums) {
7
start = Math.min(start, num);
8
end = Math.max(end, num);
9
}
10
11
int n = nums.length;
12
13
while (end - start > 1e-5) {
14
double mid = start + (end - start) / 2;
15
16
if (isValidSubarray(nums, mid, k)) {
17
start = mid;
18
}
19
else {
20
end = mid;
21
}
22
}
23
return start;
24
}
25
26
public boolean isValidSubarray(int[] nums, double target, int k) {
27
int n = nums.length;
28
double minSum = 0, sum = 0, prevSum = 0;
29
30
for (int i = 0; i < k; i++) {
31
sum += nums[i] - target;
32
}
33
34
if (sum >= 0) {
35
return true;
36
}
37
38
for (int i = k; i < n; i++) {
39
sum += nums[i] - target;
40
prevSum += nums[i - k] - target;
41
minSum = Math.min(minSum, prevSum);
42
43
if (sum > minSum) {
44
return true;
45
}
46
}
47
return false;
48
}
49
}
Copied!

3. Time & Space Complexity

Brute Force: 时间复杂度O(n^2), 空间复杂度O(1)
Binary Search: 时间复杂度O(n * log(max - min)), 空间复杂度O(1)