Best k-Day Sponsorship
Ravi runs a juice stall and has the sales of each of the last n days. A sponsor will fund exactly k consecutive days and pays according to the total sales of those days, so Ravi wants the k-day block with the highest total. Return that maximum total.
Examples
Example 1
Input: sales = [2, 1, 5, 1, 3, 2], k = 3
Output: 9
With k = 3 the possible blocks are (2, 1, 5) = 8, (1, 5, 1) = 7, (5, 1, 3) = 9 and (1, 3, 2) = 6. The best block is the third one, so the sponsor pays for a total of 9.
Example 2
Input: sales = [4, 4, 4], k = 2
Output: 8
Constraints
sales holds one day’s sales per entry, and k is between 1 and the number of days. The k days must be next to each other.
Return the largest total any k consecutive days reach.
How to solve it
Hint
“Exactly k consecutive days, maximum total” = maximum sum of a subarray of fixed length k.
Approach: Fixed-size sliding window
- Compute the sum of the first k days.
- Slide the window one day right: add the new day, subtract the day that left.
- Keep the maximum total seen.
Check with the example. Windows of 3 days: 2+1+5=8, 1+5+1=7, 5+1+3=9, 1+3+2=6 → best is 9.
Complexity: O(n) time, O(1) space.
The reference solutions in all four languages are in the Solutions tab of the workspace below.
Item 1 of 94 · updated 2026-10-12