Best k-Day Total

EasySliding Window≈ 20 min

A shop records its profit for each day of a year in the list profits; a profit can be negative. The owner wants to close for a holiday, and asks which k days in a row brought in the most, so that is not when to close.

The year wraps around: after its last day comes its first day again, so a stretch of days may run from the end of the list into its start. Return the largest total profit of any k days in a row.

Examples

text
profits = [5, -2, 1, 0, 7], k = 2   →  12
profits = [1, 2, 3, 4], k = 2       →  7
profits = [-3, -1, -2], k = 1       →  -1
profits = [4, -9, 3, 6], k = 4      →  4

In the first example the best two days are the last one and the first one: 7 + 5 = 12. When k is the whole year, as in the last example, the only stretch is every day once.

Constraints

  • Between 1 and 20,000 days, each with a profit between -10,000 and 10,000.
  • k is at least 1 and at most the number of days.
  • Aim for O(n): adding up every stretch from scratch costs n × k.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.