#1052

Grumpy Bookstore Owner

Medium
ArraySliding WindowSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can use a sliding window approach to efficiently calculate the maximum number of customers that can be satisfied by using the non-grumpy technique for a fixed number of minutes. This reduces the need for nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total number of satisfied customers without using the non-grumpy technique.
  2. 2Step 2: Use a sliding window of size 'minutes' to find the maximum number of customers that can be added to the satisfied count by considering the grumpy minutes.
  3. 3Step 3: Slide the window across the array, updating the total satisfied customers accordingly.
solution.py14 lines
1# Full working Python code
2
3def maxSatisfied(customers, grumpy, minutes):
4    total_satisfied = sum(customers[i] for i in range(len(customers)) if grumpy[i] == 0)
5    max_additional = 0
6    current_additional = 0
7    for i in range(len(customers)):
8        if grumpy[i] == 1:
9            current_additional += customers[i]
10        if i >= minutes:
11            if grumpy[i - minutes] == 1:
12                current_additional -= customers[i - minutes]
13        max_additional = max(max_additional, current_additional)
14    return total_satisfied + max_additional

Complexity note: This complexity is linear because we traverse the customers array only a couple of times, making it much more efficient than the brute-force approach.

  • 1Using a sliding window technique allows us to efficiently calculate the maximum additional customers satisfied without re-evaluating the entire array.
  • 2Understanding the problem in terms of satisfied vs. unsatisfied customers helps in formulating the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.