Minimum Penalty for a Shop Problem
Description
LeetCode Problem 2483.
You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
- if the
i^thcharacter is'Y', it means that customers come at thei^thhour - whereas
'N'indicates that no customers come at thei^thhour.
If the shop closes at the j^th hour (0 <= j <= n), the penalty is calculated as follows:
- For every hour when the shop is open and no customers come, the penalty increases by
1. - For every hour when the shop is closed and customers come, the penalty increases by
1.
Return the earliest hour at which the shop must be closed to incur a minimum penalty.
Note that if a shop closes at the j^th hour, it means the shop is closed at the hour j.
Example 1:
Input: customers = "YYNY"
Output: 2
Explanation:
- Closing the shop at the 0^th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1^st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2^nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3^rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4^th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2^nd or 4^th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
Example 2:
Input: customers = "NNNNN"
Output: 0
Explanation: It is best to close the shop at the 0^th hour as no customers arrive.
Example 3:
Input: customers = "YYYY"
Output: 4
Explanation: It is best to close the shop at the 4^th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 10^5customersconsists only of characters'Y'and'N'.
Solution
Approach: Running Penalty
If the shop closes at hour 0, the penalty is the number of 'Y' hours, since every customer arrives while it is closed.
Moving the closing time from j - 1 to j keeps the shop open for hour j - 1. If that hour is 'N' the penalty grows by 1, and if it is 'Y' the penalty drops by 1, because that customer is now served. Scan j from 1 to n, keep the smallest penalty seen, and update the answer only when the penalty is strictly smaller, so the earliest hour wins ties.
Complexity: O(n) time and O(1) space, where n is the length of customers.
class Solution:
def bestClosingTime(self, customers: str) -> int:
ans = 0
mn = cost = customers.count("Y")
for j, c in enumerate(customers, 1):
cost += 1 if c == "N" else -1
if cost < mn:
ans, mn = j, cost
return ans