Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Best total over k consecutive days

Easy · Target 10 minutes · Sliding window· Type asked at

nums[i] is the profit on day i, and may be negative. Return the largest total profit over any k consecutive days.

Examples

InputOutputWhy
nums = [2,1,5,1,3,2], k = 39Days 2 to 4: 5 + 1 + 3.
nums = [2,3,4,1,5], k = 273 + 4.
nums = [-3,-1,-4], k = 2-4Every window loses; the best loses least.

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴

Hints

Hint 1

Adding up each window from scratch costs k steps per window. What do two neighbouring windows have in common?

Hint 2

Moving the window one place right adds one element and removes one. Keep the running total.

Hint 3

Start the best at the first window's total, not at 0: every window may be negative.

Where people lose marks

  • Initialising the best to 0. With all-negative profits the answer is negative.
  • Recording the best before the first window is complete, which compares a partial sum.
  • An off-by-one in the element that leaves: when the window ends at i, the element leaving is nums[i − k].
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.