Food Truck Best Stretch

Easysliding windowAlso known as Maximum Sum Subarray of Size K

You run a food truck and log each day's profit; rainy days and festival fees mean some entries are negative. A magazine wants your best run of exactly k days in a row: the highest total profit of any k consecutive days.

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 sum to 120 - 40 + 300 = 380, -40 + 300 + 80 = 340, 300 + 80 - 200 = 180 and 80 - 200 + 150 = 30. The best is 380.

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; starting your running best at 0 would wrongly give 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. That is about n × k additions, roughly 25 million for 10,000 days and k = 5,000, and almost all repeated: neighbouring stretches share k - 1 days.

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