download

Largest sum of exactly k numbers in a row, negatives included

Algorithms~10 minReviewed 29 Oct 2026Free · No sign-in

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.

"PYTHON"
best_window([4, -7, 5, 2, -1, 6], 3)  # (7, 3)
best_window([-8, -3, -6, -2], 2)      # (-8, 2)
"CODE · PYTHON"
def best_window(values, k):
    ...
Show hints (3)
  1. "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 - 1 numbers stay. Do you need to add them up again?

  2. "WHERE BEST STARTS"

    What should best start at? Run your code on [-8, -3, -6, -2] with k = 2. If it returns 0, which window has a sum of 0?

  3. "THE FULL PLAN"

    Sum the first k numbers and use that as best. Then for each new index i, do total += values[i] - values[i - k]. Update best only when total > 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).

"SOLUTION · PYTHON"
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))
"OUTPUT"
(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:

startwindowhow the sum is foundsum
04, -7, 5added up2
1-7, 5, 22 + 2 - 40
25, 2, -10 + (-1) - (-7)6
32, -1, 66 + 6 - 57

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] with k = 2 you get 0, but no window sums to 0. Start from the sum of the first real window.
  • Skipping the check on k. Then k = 0 returns a sum of 0, and a k longer than the list returns the sum of the whole list. Neither window exists, so raise ValueError.
  • Updating on total >= best. Ties then keep the last window, not the first: [5, -5, 5, -5] with k = 2 gives (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 k numbers, 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 k numbers in collections.deque(maxlen=k). When a number arrives and the deque is full, subtract its oldest value, because append will 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 →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.