Skip to content
Algorithms for Beginners

Problems / Sliding window

Best streak

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

A shop records its profit for each day in profits. A bad day has a negative profit.

Return the highest total profit of any k days in a row.

Examples

  1. Example 1

    Input
    profits = [4, 2, 7, 1, 8, 3], k = 3
    Output
    16

    The 3-day totals are 13, 10, 16 and 12. The best is 7 + 1 + 8 = 16.

  2. Example 2

    Input
    profits = [-1, -2, -3], k = 2
    Output
    -3

    Every stretch loses money. The least bad is -1 + -2 = -3.

  3. Example 3

    Input
    profits = [5], k = 1
    Output
    5

Rules

  • profits has between 1 and 100,000 numbers.
  • k is at least 1 and at most the number of days.

Your solution

JavaScript · Press Esc then Tab to leave the editor

function bestStreak(profits, k) {
  // Return the best total of k days in a row.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in sliding window

  • Learn the sliding window pattern

    Keep a stretch of the list and slide it along instead of starting over.

  • Longest unique stretch

    Medium. Find the longest stretch of text in which no character repeats.

  • Shortest to target

    Medium. Find the fewest days in a row whose rainfall adds up to at least a target.

  • Repaint the fence

    Medium. Repaint at most k fence boards to make the longest possible stretch of one colour.

  • Hidden shuffle

    Medium. Check whether some rearrangement of a short word appears inside a longer text.

  • Two kinds

    Medium. Find the longest stretch of a list that contains at most two different values.