643.Maximum Average Subarray I

Solution 1: accepted 22ms

Iteration.
Time: O(n)
Space: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public double findMaxAverage(int[] nums, int k) {
int len = nums.length;
if (len < k) return 0;
double sum = 0;
for(int i = 0; i < k; i++) {
sum += nums[i] / (double) k;
}
double max = sum;
for(int i = 1; i < len - k + 1; i++) {
sum = sum - nums[i-1] / (double) k + nums[i+k-1] / (double) k;
max = Math.max(max, sum);
}
return max;
}

Solution 2: accepted 19ms

Calculate the average at last - be flexible man.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public double findMaxAverage(int[] nums, int k) {
int len = nums.length;
if (len < k) return 0;
double sum = 0;
for(int i = 0; i < k; i++) {
sum += nums[i];
}
double max = sum;
for(int i = 1; i < len - k + 1; i++) {
sum = sum - nums[i - 1] + nums[i + k - 1];
max = Math.max(max, sum);
}
return max / (double) k;
}