Food Truck Best Stretch

Easysliding windowAlso known as Maximum Sum Subarray of Size K

You run a food truck and keep a log of each day's profit. Rainy days, broken fryers and festival fees mean some days lose money, so the log has negative numbers too.

A magazine wants to feature your truck and asks for your best run of exactly k days in a row. You want to know the highest total profit any k consecutive days in your log reached.

Your task

Write bestStretch(profits, k). Return the largest sum of any k consecutive entries of profits.

The answer can be negative if every stretch of k days lost money.

bestStretch(profits: int[], k: int) → int

Examples

Example 1
Input
profits = [120, -40, 300, 80, -200, 150]
k = 3
Output
380
Why

The 3-day stretches add up to 120 - 40 + 300 = 380, then -40 + 300 + 80 = 340, then 300 + 80 - 200 = 180, then 80 - 200 + 150 = 30. The best is 380, from the first three days.

Example 2
Input
profits = [-50, -20, -90, -10]
k = 2
Output
-70
Why

Every 2-day stretch lost money: -70, -110, -100. The best is -70. If you start your running best at 0, you would wrongly answer 0.

Constraints

  • 1 ≤ k ≤ profits.length ≤ 10,000
  • -10,000 ≤ profits[i] ≤ 10,000
Start with brute force

For every starting day, add up the next k profits, and keep the largest total.

That is about n × k additions. With 10,000 days and k = 5,000 it is roughly 25 million additions, almost all of them repeated: neighbouring stretches share k - 1 days, and you add those same days up again every time.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code