Leetcode 643. Maximum Average Subarray I
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.
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Input: nums = [5], k = 1
Output: 5.00000
Q: Can n
be smaller than k
?
A: No, n
will always be greater than or equal to k
.
Q: Can the array have negative numbers? A: Yes, the array can have negative numbers.
Q: Is the array always non-empty?
A: Yes, the array is non-empty, and k
is a valid number.
Q: How large can n
and k
be?
A: Typically, constraints are given such that both n
and k
will be within reasonable limits for performance in an O(n) approach.
To find the subarray of length k
with the maximum average, follow these steps:
k
elements. This will be the initial sum and average.k
to n - 1
:
nums[i - k]
).nums[i]
).k
to get the maximum average.#include <vector>
#include <limits>
using namespace std;
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int n = nums.size();
int current_sum = 0;
// Compute the sum of the first k elements
for (int i = 0; i < k; ++i) {
current_sum += nums[i];
}
int max_sum = current_sum;
// Sliding window to find the maximum sum of k consecutive elements
for (int i = k; i < n; ++i) {
current_sum += nums[i] - nums[i - k];
if (current_sum > max_sum) {
max_sum = current_sum;
}
}
// Calculate the maximum average
return (double)max_sum / k;
}
};
k
elements takes O(k)
.O(n - k)
, which is O(n)
.Thus, the overall time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?