LeetCode 1052. Grumpy Bookstore Owner

Problem link

This is another sliding window problem. At first glance, this doesn’t seem to be a straightforward sliding window.
Let’s take a look at it closely.

Let’s break down the problem first.
1. We need to keep track of the total number of satisfied customers. This is easy.
2. We also need to find out unsatisfied customers who could be satisfied if the owner decides not to be grumpy for n minutes

Do you see how this is sliding window now?
This problem is about adding the total number of satisfied customers and customers who can be satisfied for n minutes.
Answer = # satisfied + # unsatisfied for n minutes
And the second term is the sliding window of size n. What is the max number of unsatisfied customers for n minutes?

Sliding Window

Brute force option of checking max # unsatisfied customers for n minutes is like below.
1. traverse the array with window size n
2. count number of unsatisfied customers

This is O(n^2) time complexity. We aren’t going to use brute force here. But this is mentioned to see how this can be optimized.

As you can see, in each sliding window, there is a redundant count of unsatisfied customers.
Refer to this link to see the visual example of a redundant count in sliding window.

How can you avoid this?
You remove unsatisfied customers from the window from the left side when they are out of the window.
And you add new unsatisfied customers to the right side of the window.
Here is the solution in C++

int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
    int numComplained = 0;
    int numSatisfied = 0;
    for (size_t i = 0; i < minutes; ++i) {
        numComplained += grumpy[i] == 1 ? customers[i] : 0;
        numSatisfied += grumpy[i] == 0 ? customers[i] : 0;
    }

    int maxComplained = numComplained;
    for (size_t i = minutes; i < customers.size(); ++i) {
        numSatisfied += grumpy[i] == 0 ? customers[i] : 0;
        numComplained -= grumpy[i-minutes] == 1 ? customers[i-minutes] : 0;
        numComplained += grumpy[i] == 1 ? customers[i] : 0;
        maxComplained = max(maxComplained, numComplained);
    }

    return numSatisfied + maxComplained;
}

Leave a Reply

Your email address will not be published. Required fields are marked *