The best k days in a row
EasyStuck?
Show a hintHide the hint
Do not re-add the whole window. Sliding one step adds one number and removes one, so keep a running sum and update both ends.
The ideas behind this problem
Next in this lesson
The first negative number in every windowGiven a list of numbers and a size k, find the largest sum of any k consecutive numbers.
Worked example#
For [2, 1, 5, 1, 3, 2] with k = 3:
| window | numbers | sum |
|---|---|---|
| 0 to 2 | 2, 1, 5 | 8 |
| 1 to 3 | 1, 5, 1 | 7 |
| 2 to 4 | 5, 1, 3 | 9 |
| 3 to 5 | 1, 3, 2 | 6 |
The best is 9.
The idea#
Adding up each window from scratch means k additions per window, so n times k in total. With a window of a thousand over a hundred thousand numbers that is a hundred million additions for what is really a very simple question.
Look at two neighbouring windows. They share everything except the two ends. Sliding one step to the right means exactly one number joins and exactly one number leaves:
new sum = old sum + nums[right] - nums[left - 1]
So build the first window once, then slide it, doing one addition and one subtraction per step. The work no longer depends on k at all.
This is the whole idea behind a fixed sliding window, and the shape comes back constantly: averages, counts of vowels, how many even numbers are in each window. What changes is what you keep as the window moves. Here it is a running sum, and every one of those updates has to be reversible: whatever adding a number does, removing it has to undo.
Constraints#
1 <= k <= n <= 100000-10000 <= nums[i] <= 10000
Input
nums is a count then that many integers. k is a single integer on the next line.
Output
Print the largest sum.
Examples
Input
6 2 1 5 1 3 2 3
Output
9
The window on 5, 1, 3 is the best of the four.
Input
4 1 2 3 4 4
Output
10
The window is the whole list, so there is only one answer.
Input
5 -3 -1 -4 -1 -5 2
Output
-4
Every number is negative, so the answer is the least bad pair.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.