#2483

Minimum Penalty for a Shop

Medium
StringPrefix SumPrefix SumSuffix Sum
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses prefix sums to efficiently calculate penalties without nested loops. We can precompute how many 'N's are before any hour and how many 'Y's are after it, allowing us to compute the penalty in constant time for each closing hour.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a prefix sum array to count 'N's up to each hour.
  2. 2Step 2: Create a suffix sum array to count 'Y's from each hour to the end.
  3. 3Step 3: For each hour, calculate the penalty using the prefix and suffix sums.
  4. 4Step 4: Track the minimum penalty and the corresponding hour.
  5. 5Step 5: Return the hour with the minimum penalty.
solution.py16 lines
1def bestClosingTime(customers):
2    n = len(customers)
3    prefixN = [0] * (n + 1)
4    suffixY = [0] * (n + 1)
5    for i in range(n):
6        prefixN[i + 1] = prefixN[i] + (1 if customers[i] == 'N' else 0)
7    for i in range(n - 1, -1, -1):
8        suffixY[i] = suffixY[i + 1] + (1 if customers[i] == 'Y' else 0)
9    min_penalty = float('inf')
10    best_hour = 0
11    for j in range(n + 1):
12        penalty = prefixN[j] + suffixY[j]
13        if penalty < min_penalty:
14            min_penalty = penalty
15            best_hour = j
16    return best_hour

Complexity note: This complexity is due to the linear scans needed to create the prefix and suffix arrays, allowing us to compute penalties in constant time thereafter.

  • 1Understanding how to calculate penalties efficiently is crucial.
  • 2Using prefix and suffix sums can significantly reduce time complexity.

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