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

The best stretch to stay calm

Medium · Target 15 minutes · Sliding window· Type asked at

A shop is open for n minutes. customers[i] people are served in minute i. In minutes where moody[i] = 1 the owner is short-tempered and those customers leave unhappy; when moody[i] = 0 they leave satisfied. Once a day the owner can stay calm for k consecutive minutes, and every customer served in that stretch is satisfied. Return the largest possible number of satisfied customers.

Examples

InputOutputWhy
customers = [1,0,1,2,1,1,7,5], moody = [0,1,0,1,0,1,0,1], k = 316Stay calm in minutes 5 to 7: 1 + 1 + 1 + 1 + 7 + 5.
customers = [4], moody = [1], k = 14
customers = [3,2,5], moody = [0,0,0], k = 210Nobody is unhappy anyway.

Constraints

  • 1 ≤ k ≤ n ≤ 2 × 10⁴
  • 0 ≤ customers[i] ≤ 1000
  • moody[i] is 0 or 1

Hints

Hint 1

Customers in calm minutes are satisfied whatever the owner does. Count them once.

Hint 2

The window only matters in moody minutes. How many extra customers does a window starting at i rescue?

Hint 3

The extra is the sum of customers[j] × moody[j] over the window: a fixed-window sum.

Where people lose marks

  • Adding the calm-minute customers inside the window as well, which counts them twice.
  • Sliding over all customers instead of the rescued ones.
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.