Problem Description
A bookstore owner has a store open for n minutes. Each minute, customers[i] customers enter and immediately leave after that minute. The owner is grumpy during some minutes (indicated by grumpy[i] == 1) and, as a result, customers during those minutes are unsatisfied. However, the owner can use a secret technique once to remain not grumpy for a consecutive block of "minutes" minutes, turning those potentially unsatisfied customers into satisfied ones. The task is to choose the best time window to maximize the total number of satisfied customers over the day.
Key Insights
- The customers during minutes when the owner is not grumpy (grumpy[i] == 0) are always satisfied. Sum these as a base value.
- Applying the secret technique makes unsatisfied customers during the chosen window become satisfied. So, for a window of length "minutes", only consider the additional gain from minutes when grumpy[i] == 1.
- Use a sliding window of fixed size "minutes" over the array to calculate the potential extra gain.
- The final answer is the sum of the base satisfied customers and the maximum extra gain obtained from any valid window.
Space and Time Complexity
Time Complexity: O(n) – We traverse the array once for the base sum and then use a sliding window approach. Space Complexity: O(1) – Only constant extra space is used.
Solution
We first calculate the number of satisfied customers when the owner is not grumpy (base satisfaction). Then, we compute the additional gain if we were to suppress the owner's grumpiness for a consecutive block of "minutes" minutes. This is done by using a sliding window technique to sum the number of customers during grumpy minutes within each window and updating the maximum gain found. Finally, we add the base satisfaction to this maximum extra gain to get the result.