Recomputing the sum of every length-k slice costs O(n·k). A sliding window keeps one running sum and updates it in O(1) as the window moves one position to the right.
Given a list of integers nums and a positive integer k, return the maximum sum of any contiguous subarray of length exactly k.
Examples
Input: nums = [2, 1, 5, 1, 3, 2], k = 3
Output: 9
Explanation: [5, 1, 3] has the largest sum.
Input: nums = [-1, -2, -3, -4], k = 2
Output: -3
Explanation: [-1, -2] is the best you can do.
Constraints
1 <= k <= len(nums) <= 10**4- Elements may be negative.
- Aim for O(n) time.
Goals
- Maintain the sum of a fixed-size window as it slides one step at a time
- Update a running total by adding the entering element and subtracting the leaving one
- Avoid recomputing a sum from scratch for every window