Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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:
Input: nums = [1,12,-5,-6,50,3], k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
Input: nums = [5], k = 1 Output: 5.00000
Constraints:
n == nums.length1 <= k <= n <= 105-104 <= nums[i] <= 104Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Sliding Window
[1,12,-5,-6,50,3] 4
[5] 1
maximum-average-subarray-ii)k-radius-subarray-averages)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #643: Maximum Average Subarray I
class Solution {
public double findMaxAverage(int[] nums, int k) {
int s = 0;
for (int i = 0; i < k; ++i) {
s += nums[i];
}
int ans = s;
for (int i = k; i < nums.length; ++i) {
s += (nums[i] - nums[i - k]);
ans = Math.max(ans, s);
}
return ans * 1.0 / k;
}
}
// Accepted solution for LeetCode #643: Maximum Average Subarray I
func findMaxAverage(nums []int, k int) float64 {
s := 0
for _, x := range nums[:k] {
s += x
}
ans := s
for i := k; i < len(nums); i++ {
s += nums[i] - nums[i-k]
ans = max(ans, s)
}
return float64(ans) / float64(k)
}
# Accepted solution for LeetCode #643: Maximum Average Subarray I
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
ans = s = sum(nums[:k])
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
ans = max(ans, s)
return ans / k
// Accepted solution for LeetCode #643: Maximum Average Subarray I
impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let k = k as usize;
let n = nums.len();
let mut s = nums.iter().take(k).sum::<i32>();
let mut ans = s;
for i in k..n {
s += nums[i] - nums[i - k];
ans = ans.max(s);
}
f64::from(ans) / f64::from(k as i32)
}
}
// Accepted solution for LeetCode #643: Maximum Average Subarray I
function findMaxAverage(nums: number[], k: number): number {
let s = 0;
for (let i = 0; i < k; ++i) {
s += nums[i];
}
let ans = s;
for (let i = k; i < nums.length; ++i) {
s += nums[i] - nums[i - k];
ans = Math.max(ans, s);
}
return ans / k;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.