Open songyy5517 opened 6 months ago
Approach: Sliding Window
sum = nums[0:k-1]
: the sum of the current window;max = sum
: record the global max sum.k
:
max * 1.0 / k
.Complexity Analysis
class Solution {
public double findMaxAverage(int[] nums, int k) {
// Intuition: Double pointers & Sliding window
// 1. Exception handling
if (nums == null || nums.length < k)
return 0;
// 2. Initiate sum
int sum = 0;
for (int i = 0; i < k; i++)
sum += nums[i];
int max_sum = sum;
// 3. Loop though with sliding window
for (int i = k; i < nums.length; i++){
sum = sum + nums[i] - nums[i - k];
max_sum = Math.max(max_sum, sum);
}
return max_sum * 1.0 / k ;
}
}
2024/5/13
You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than $10^{-5}$ will be accepted.
Example 1:
Example 2:
Intuition This problem is to find a contiguous subarray in a array. A striaghtforward idea is to iterate over the array with a sliding window. For each step, calculate the sum of the current window and compare it with the max value, then move the window to the next step.