Classic sliding window, you compute the sum of the first k elements then slide across the array updating the sum as you go.
Use a sliding window of size k to compute the sum of each contiguous subarray, tracking the maximum sum and its starting index. Return the subarray corresponding to the maximum sum.
Pro tip: Avoid floating-point division by comparing sums directly; only divide at the end to return the average if needed. This prevents precision issues and improves performance.
Confirm that the array contains integers, k is positive and ≤ array length, and that we need to return the subarray (not just the average).
Compute the sum of the first k elements and set it as the initial maximum sum. Record the starting index (0).
Iterate from index k to the end, updating the window sum by subtracting the element leaving the window and adding the new element. If the new sum exceeds the maximum, update the maximum and record the new starting index.
After the loop, extract the subarray from the recorded starting index of length k and return it. Optionally compute the average by dividing the maximum sum by k.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.