Grumpy Bookstore Owner Problem
Description
LeetCode Problem 1052.
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 the customers that enter the store at the start of the i^th 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 i^th minute, and is 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.
Example 1:
Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3
Output: 16
Explanation:
The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
Example 2:
Input: customers = [1], grumpy = [0], minutes = 1
Output: 1
Constraints:
n == customers.length == grumpy.length1 <= minutes <= n <= 2 * 10^40 <= customers[i] <= 1000grumpy[i]is either0or1.
Solution
Approach: Sliding Window
Split the customers into two groups:
- Customers in minutes where the owner is not grumpy are satisfied anyway, wherever the technique is used. Add them all up.
- Customers in grumpy minutes are satisfied only if their minute falls inside the
minutes-long window where the technique is used.
So we only need the window of length minutes that covers the most grumpy-minute customers. Slide it across the day: add customers[i] * grumpy[i] for the minute entering on the right, subtract the same quantity for the minute leaving on the left, and track the best window seen.
The answer is the always-satisfied total plus the best window. Multiplying by grumpy[i] makes calm minutes count zero inside the window, so they are not counted twice.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
# Customers in calm minutes are satisfied no matter where the technique is used.
calm = sum(c for c, g in zip(customers, grumpy) if g == 0)
# Slide a window of `minutes` and track the grumpy-minute customers it would win back.
window = best = 0
for i in range(len(customers)):
window += customers[i] * grumpy[i]
if i >= minutes:
window -= customers[i - minutes] * grumpy[i - minutes]
best = max(best, window)
return calm + best