|
| 1 | +# Maximum Sum of Subarray with Size K |
| 2 | + |
| 3 | +Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k. |
| 4 | + |
| 5 | +## Examples |
| 6 | + |
| 7 | +Example 1 |
| 8 | + |
| 9 | +```text |
| 10 | +Input: nums = [2, 1, 5, 1, 3, 2], k = 3 |
| 11 | +Output: 9 |
| 12 | +Explanation: The subarray with the maximum sum is [5, 1, 3] with a sum of 9. |
| 13 | +``` |
| 14 | + |
| 15 | +## Solution |
| 16 | + |
| 17 | +We start by extending the window to size k. Whenever our window is of size k, we first compute the sum of the window and |
| 18 | +update max_sum if it is larger than max_sum. Then, we contract the window by removing the leftmost element to prepare for |
| 19 | +the next iteration. Note how we calculate the sum of the window incrementally by adding the new element and removing from |
| 20 | +the previous sum. |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + |
0 commit comments