Largest sum of exactly k numbers in a row, negatives included
Question
You get a list of daily balance changes and a window size k. Find the largest sum of exactly k days in a row. Return the sum and the index where that window starts. If windows tie, return the earliest one. If no window of size k exists, raise ValueError. Aim for O(n) time.
best_window([4, -7, 5, 2, -1, 6], 3) # (7, 3) best_window([-8, -3, -6, -2], 2) # (-8, 2)
def best_window(values, k): ...
Show hints (3)
- "REUSE THE SUM"
When the window moves one step right, one number leaves on the left and one joins on the right. The other
k - 1numbers stay. Do you need to add them up again? - "WHERE BEST STARTS"
What should
beststart at? Run your code on[-8, -3, -6, -2]withk = 2. If it returns 0, which window has a sum of 0? - "THE FULL PLAN"
Sum the first
knumbers and use that asbest. Then for each new indexi, dototal += values[i] - values[i - k]. Updatebestonly whentotal > best, so ties keep the earliest window.
Show checked explanation
Sum the first k numbers. Then slide the window one step at a time: add the number that joins and subtract the one that leaves. Start best from the first window's sum, not from 0, so an all-negative list still works. That is O(n) time instead of O(n·k).
def best_window(values, k): if not 1 <= k <= len(values): raise ValueError("no window of size k") total = sum(values[:k]) best, best_start = total, 0 for i in range(k, len(values)): total += values[i] - values[i - k] if total > best: best, best_start = total, i - k + 1 return best, best_start print(best_window([4, -7, 5, 2, -1, 6], 3)) print(best_window([-8, -3, -6, -2], 2)) print(best_window([5, -5, 5, -5], 2))
(7, 3) (-8, 2) (0, 0)
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is [4, -7, 5, 2, -1, 6] with k = 3:
| start | window | how the sum is found | sum |
|---|---|---|---|
| 0 | 4, -7, 5 | added up | 2 |
| 1 | -7, 5, 2 | 2 + 2 - 4 | 0 |
| 2 | 5, 2, -1 | 0 + (-1) - (-7) | 6 |
| 3 | 2, -1, 6 | 6 + 6 - 5 | 7 |
The best sum is 7, and that window starts at index 3. Only the first window is added up in full. Every later one costs one addition and one subtraction, so the whole pass is O(n). Adding up every window from scratch would be O(n·k).
Negative numbers don't change the method. The window still holds exactly k values. Negative values only make some sums smaller.
Now try [-8, -3, -6, -2] with k = 2. The window sums are -11, -9 and -8, so the answer is (-8, 2). If best started at 0, the function would return 0, a sum that no window has.
A sum of 0 and "no window" are different results. In [5, -5, 5, -5] with k = 2, every window sums to 0, so (0, 0) is a real answer. With k = 4 there is exactly one window, and the answer is again (0, 0). With k = 0, k = 5 or an empty list, no window exists, so the function raises ValueError.
Common mistakes
- Starting with
best = 0. On[-8, -3, -6, -2]withk = 2you get 0, but no window sums to 0. Start from the sum of the first real window. - Skipping the check on
k. Thenk = 0returns a sum of 0, and aklonger than the list returns the sum of the whole list. Neither window exists, so raiseValueError. - Updating on
total >= best. Ties then keep the last window, not the first:[5, -5, 5, -5]withk = 2gives(0, 2)instead of(0, 0). - Using Kadane's trick of starting over when the running sum turns negative. That trick is for windows of any length. Here every window holds exactly
knumbers, so you can't skip the bad ones.
Follow-up questions
- "The numbers now arrive as a stream, one at a time." You can't look back at old input, so keep the last
knumbers incollections.deque(maxlen=k). When a number arrives and the deque is full, subtract its oldest value, becauseappendwill drop it. Then append the new number and add it to the total. This needs O(k) extra memory. - "Now the window can be any length. What changes?" That is the maximum subarray problem, solved by Kadane's algorithm. At each index, either extend the best window that ends just before it, or start a new window there. Keep whichever sum is larger. The fixed-size slide no longer applies.
- "What if the values are floats?" Each addition and subtraction rounds a little. Over a long list, the running total can drift away from the true window sum. Add the window up again from scratch every so often, or store money as whole cents in integers.
What a strong answer covers
Asks what to return when no window exists. Starts best from a real window and explains why the slide is O(n). Handles ties on purpose and tests a list where every number is negative.
Open in interactive practice deck →