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.
A market stall writes down each day's profit in nums (a loss is negative). For a positive integer k, find the best stretch of exactly k consecutive days: return the largest total of any k neighbouring entries.
Examples
Input: nums = [4, 2, 7, 1, 6, 3], k = 3
Output: 14
Explanation: [7, 1, 6] has the largest sum.
Input: nums = [-5, -2, -6, -3], k = 2
Output: -7
Explanation: [-5, -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