Maximum Sum Subarray of Size K
Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.
Return the maximum sum.
Examples
nums = [2, 1, 5, 1, 3, 2], k = 39nums = [2, 3, 4, 1, 5], k = 27Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.length
💡 Hints
Hint 1
Calculate the sum of the first k elements. Then slide the window: add the new right element and subtract the old left element.
Hint 2
This avoids recalculating the entire window sum — just one addition and one subtraction per step.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Classic fixed-size sliding window. First calculate the sum of the initial window. Then slide right: add the new element entering the window, subtract the element leaving. Track the maximum sum.
Sliding window with two pointers advances right across array and shrinks left when window sum exceeds or matches target.
Maintains constant extra space with scalar pointers and a running sum variable.
🌍 Real-World Use Cases
Finding the 7-day window with the highest total viewership to plan marketing campaigns and content releases.
Identifying the k-hour window with the highest order volume to optimize warehouse staffing.
🔍 Dry Run
First window [2,1,5]: sum = 2+1+5 = 8