sagelearnai

Grumpy Bookstore Owner

Difficulty: Medium · Pattern: Sliding Window · LeetCode #1052

At minute i, customers[i] customers enter. If the owner is grumpy that minute (grumpy[i] = 1), those customers are unsatisfied. The owner can stay calm for one stretch of minutes consecutive minutes. Return the maximum number of satisfied customers.

Examples

text
customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3  →  16
customers = [1], grumpy = [0], minutes = 1                              →  1

Hints

  1. Customers in non-grumpy minutes are satisfied regardless.
  2. The technique only adds the grumpy-minute customers inside the chosen window. Maximize that with a fixed window.

Approach

base = the sum of customers[i] where grumpy[i] == 0. Slide a window of size minutes over the extra gain customers[i] · grumpy[i] and track its maximum sum. The answer is base + maxGain. O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def maxSatisfied(customers, grumpy, minutes):
    base = sum(c for c, g in zip(customers, grumpy) if g == 0)
    gain = best = 0
    for i, (c, g) in enumerate(zip(customers, grumpy)):
        gain += c * g
        if i >= minutes:
            gain -= customers[i - minutes] * grumpy[i - minutes]
        best = max(best, gain)
    return base + best
JavaScript solution
function maxSatisfied(customers, grumpy, minutes) {
  let base = 0, gain = 0, best = 0;
  for (let i = 0; i < customers.length; i++) {
    if (!grumpy[i]) base += customers[i];
    gain += customers[i] * grumpy[i];
    if (i >= minutes) gain -= customers[i - minutes] * grumpy[i - minutes];
    best = Math.max(best, gain);
  }
  return base + best;
}