Maximum Sum Subarray of Size K
Master this topic with zero to advance depth.
Maximum Sum Subarray of Size K
Given an array of integers nums and a positive integer k, find the maximum sum of any contiguous subarray of size k.
Visual Representation
nums = [2, 1, 5, 1, 3, 2], k = 3
Step 1: [2, 1, 5], 1, 3, 2 (Sum = 8)
Step 2: 2, [1, 5, 1], 3, 2 (Sum = 7)
Step 3: 2, 1, [5, 1, 3], 2 (Sum = 9) -> MAX
Step 4: 2, 1, 5, [1, 3, 2] (Sum = 6)Examples
Subarray [5, 1, 3] has the maximum sum of 9.
Level I: Brute Force (Nested Loops)
Intuition
The most basic way to solve this is to check every possible contiguous subarray of size k and calculate its sum. We keep track of the maximum sum found so far.
Thought Process
- Iterate through every possible starting index
ifrom0ton - k. - For each
i, start another loop to sum up the nextkelements. - Update
maxSumif the current subarray sum is larger.
Pattern Identification
This is a Naive Search pattern. We are re-calculating the sum for overlapping parts of subarrays, which is the main bottleneck.
Detailed Dry Run
| Outer Loop (i) | Inner Loop (j) | Current Sum | Max Sum | Action |
|---|---|---|---|---|
| 0 | 0, 1, 2 | 2+1+5 = 8 | 8 | Init Max |
| 1 | 1, 2, 3 | 1+5+1 = 7 | 8 | No Change |
| 2 | 2, 3, 4 | 5+1+3 = 9 | 9 | Update Max |
| 3 | 3, 4, 5 | 1+3+2 = 6 | 9 | No Change |
Level II: Prefix Sums (O(N) Space)
Intuition
We can precompute a prefix sum array where prefix[i] stores the sum of elements from 0 to i-1. The sum of any subarray nums[i...j] can then be calculated in as prefix[j+1] - prefix[i].
Thought Process
- Create an array
prefixof sizen + 1. - Fill
prefixsuch thatprefix[i+1] = prefix[i] + nums[i]. - Iterate from
i = 0ton - kand calculatesum = prefix[i+k] - prefix[i]. - Update
maxSumaccordingly.
Pattern: Space-Time Tradeoff
This approach reduces the calculation time to per subarray but uses extra space.
Level III: Optimal (Sliding Window)
Intuition
Thought Process
We can observe that two consecutive subarrays of size k share k-1 elements. Instead of re-summing everything, we can 'slide' the window: add the next element (Right) and subtract the element that is no longer in the window (Left).
Pattern: Sliding Window (Fixed Size)
- Expand: Add
nums[right]towindowSum. - Shrink/Slide: When
right >= k - 1, the window is full. Update the result, then subtractnums[left]and incrementleftto prepare for the next step.
Mandatory Variables
left: Pointer to the start of the window.windowSum: Current sum of thekelements.maxSum: Best sum found so far.
Detailed Dry Run
| Step | Right | Left | windowSum | maxSum | Action |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 2 | 0 | Expand |
| 2 | 1 | 0 | 3 | 0 | Expand |
| 3 | 2 | 0 | 8 | 8 | Window Full, Update Max |
| 4 | 3 | 1 | 7 | 8 | Slide (Sub 2, Add 1) |
| 5 | 4 | 2 | 9 | 9 | Slide (Sub 1, Add 3), Update Max |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.