During minutei,customers[i]customers enter. They are satisfied whengrumpy[i] == 0and unsatisfied whengrumpy[i] == 1. The owner may suppress grumpiness for exactlyminutesconsecutive minutes. Return the maximum number of satisfied customers.
Some customers are satisfied regardless of which window the owner chooses. Whenever grumpy[i] == 0, add customers[i] to the baseline. Choosing the window cannot make those customers any more satisfied because they are already counted.
The chosen window can help only during minutes when grumpy[i] == 1. If the window covers minute i, the customers[i] customers from that minute become satisfied. A calm minute contributes nothing extra because its customers are already included in the baseline.
The remaining task is to find the length-minutes window containing the largest number of otherwise unsatisfied customers. Maintain that extra gain with a fixed-size sliding window.
The final answer is the customers who were already satisfied plus the largest extra gain from one chosen window: baseline + best_gain.
Which customers belong in the baseline?
- baseline
- 0
- possible extra
- not built
For each length-minutes window, add customers[i] only when grumpy[i] == 1. Those are the customers who would become satisfied if the owner suppressed grumpiness during that block. Keep the largest block sum.
Which two-minute block creates the largest extra gain?
- left
- 0
- right
- 0
- customers in window
- 4
- newly satisfied
- 0
- best gain
- not ready
The baseline counts customers from minutes where grumpy[i] == 0. The window gain counts customers only from covered minutes where grumpy[i] == 1. Since each minute belongs to only one of those groups, adding the two totals does not count any customer twice.
The baseline pass, first-window setup, and remaining window scan process each minute a constant number of times, giving O(n) time. The algorithm stores only the baseline, current window gain, and best gain, so auxiliary space is O(1).