Maximum Average Subarray I LT643

时间:2023-03-09 00:22:53
Maximum Average Subarray I LT643

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4

Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

  1. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

Idea 1: window with width k. Assume we already know the sum of element from index left to index right(right = left + k -1), now how to extend the solution from the index left + 1 to index right + 1? Use two pointers moving from left to right, add the element on the right end and take away the element on the left end.

Time complexity: O(n), one pass

Space complexity: O(1)

写loop记住检查终止条件 避免死循环

class Solution {
public double findMaxAverage(int[] nums, int k) {
double maxAverage = Integer.MIN_VALUE;
double sum = 0; for(int left = 0, right = 0; right < nums.length; ++right) {
if(right >= k) {
sum -= nums[left];
++left;
}
sum += nums[right];
if(right >= k-1) {
maxAverage = Math.max(maxAverage, sum/k);
}
} return maxAverage;
}
}

maxAvearge = maxSum/k

class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0; int right = 0;
while(right < k) {
sum += nums[right];
++right;
}
double maxSum = sum; for(int left = 0; right < nums.length; ++right, ++left) {
sum = sum + nums[right] - nums[left];
maxSum = Math.max(maxSum, sum);
} return maxSum/k;
}
}

instead of using two variables, one variable is enough

class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0; for(int i = 0; i < k; ++i) {
sum += nums[i];
} double maxSum = sum; for(int i = k; i < nums.length; ++i) {
sum = sum + nums[i] - nums[i-k];
maxSum = Math.max(maxSum, sum);
} return maxSum/k;
}
}

Idea 1.a Use cumulative sum, the sum of subarray = cumu[i] - cumu[i-k].

Time complexity: O(n), two passes

Space complexity: O(n)

class Solution {
public double findMaxAverage(int[] nums, int k) {
int sz = nums.length;
int[] cumu = new int[sz]; cumu[0] = nums[0];
for(int i = 1; i < sz; ++i) {
cumu[i] = cumu[i-1] + nums[i];
} double maxSum = cumu[k-1];
for(int i = k; i < sz; ++i) {
maxSum = Math.max(maxSum, cumu[i] - cumu[i-k]);
} return maxSum/k;
}
}