Grumpy Bookstore Owner - Problem

There is a bookstore owner that has a store open for n minutes. You are given an integer array customers of length n where customers[i] is the number of customers that enter the store at the start of the ith minute and all those customers leave after the end of that minute.

During certain minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and 0 otherwise. When the bookstore owner is grumpy, the customers entering during that minute are not satisfied. Otherwise, they are satisfied.

The bookstore owner knows a secret technique to remain not grumpy for minutes consecutive minutes, but this technique can only be used once. Return the maximum number of customers that can be satisfied throughout the day.

Input & Output

Example 1 — Basic Case
$ Input: customers = [1,0,1,2,1], grumpy = [1,0,1,1,0], minutes = 3
Output: 4
💡 Note: Base satisfied customers: 0 (index 1) + 1 (index 4) = 1. Apply technique to minutes 1-3: gain 0+1+2 = 3 additional. Total = 1 + 3 = 4.
Example 2 — Technique at Start
$ Input: customers = [1], grumpy = [0], minutes = 1
Output: 1
💡 Note: Owner is naturally not grumpy, so 1 customer is already satisfied. Using technique doesn't change anything.
Example 3 — All Grumpy
$ Input: customers = [2,3,1], grumpy = [1,1,1], minutes = 2
Output: 5
💡 Note: Base satisfied: 0 (all grumpy). Best technique window covers first 2 minutes: gain 2+3 = 5. Total = 0 + 5 = 5.

Constraints

  • 1 ≤ customers.length == grumpy.length ≤ 2 × 104
  • 0 ≤ customers[i] ≤ 1000
  • grumpy[i] is either 0 or 1
  • 1 ≤ minutes ≤ customers.length

Visualization

Tap to expand
Grumpy Bookstore Owner INPUT customers[]: 1 0 1 2 1 grumpy[]: 1 0 1 1 0 Grumpy (1) Happy (0) minutes = 3 (Technique window size) Store Timeline: 0 1 2 3 4 ALGORITHM STEPS 1 Calculate Base Satisfied Sum customers when not grumpy Base = 0 + 1 = 1 2 Sliding Window Setup Find extra customers saved in each window of size 3 3 Window Calculations [0-2]: 1+0+1=2 [1-3]: 0+1+2=3 MAX [2-4]: 1+2+0=3 4 Combine Results Base + Max Extra Saved 1 + 3 = 4 FINAL RESULT Optimal Technique Window: customers: 1 0 1 2 1 Technique Applied Satisfied Customers: Minute 1: 0 (happy) Minute 2,3: 1+2=3 (technique) Minute 4: 1 (happy) Maximum Satisfied 4 OK - Optimal Solution Found Key Insight: Use sliding window to find the optimal position for the technique. First calculate base satisfied customers (when owner is naturally happy). Then find the window that saves maximum additional customers from grumpy minutes. Time: O(n), Space: O(1) TutorialsPoint - Grumpy Bookstore Owner | Optimal Sliding Window Solution
Asked in
Amazon 12 Google 8 Microsoft 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen