Grumpy Bookstore Owner — LeetCode 1052 Python Solution

MediumArraySliding Window
Problem
#1052
Reading time
2 min

The 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 the customers that enter the store at the start of the ith minute and all those customers leave after the end of that minute.

Python solution

Python
class Solution:
    def maxSatisfied(
        self, customers: List[int], grumpy: List[int], minutes: int
    ) -> int:
        mx = cnt = sum(c * g for c, g in zip(customers[:minutes], grumpy))
        for i in range(minutes, len(customers)):
            cnt += customers[i] * grumpy[i]
            cnt -= customers[i - minutes] * grumpy[i - minutes]
            mx = max(mx, cnt)
        return sum(c * (g ^ 1) for c, g in zip(customers, grumpy)) + mx

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array `customers`
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1052. Grumpy Bookstore Owner is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1052. Grumpy Bookstore Owner?
LeetCode 1052. Grumpy Bookstore Owner is rated Medium on LeetCode.
What is the time complexity of LeetCode 1052. Grumpy Bookstore Owner?
The Python solution on this page runs in O(n), where n is the length of the array `customers`.
What is the space complexity of LeetCode 1052. Grumpy Bookstore Owner?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1052. Grumpy Bookstore Owner cover?
LeetCode 1052. Grumpy Bookstore Owner is tagged Array and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview