2483. Minimum Penalty for a Shop
Description
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
ithcharacter is'Y', it means that customers come at theithhour - whereas
'N'indicates that no customers come at theithhour.
If the shop closes at the jth 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 jth hour, it means the shop is closed at the hour j.
Example 1:
Input: customers = "YYNY" Output: 2 Explanation: - Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty. - Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty. - Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty. - Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty. - Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty. Closing the shop at 2nd or 4th 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 0th hour as no customers arrive.
Example 3:
Input: customers = "YYYY" Output: 4 Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 105customersconsists only of characters'Y'and'N'.
Solutions
Solution 1: Enumeration
If the shop closes at hour \(0\), then the cost is the number of character 'Y' in \(\textit{customers}\). We initialize the answer variable \(\textit{ans}\) to \(0\), and the cost variable \(\textit{cost}\) to the number of character 'Y' in \(\textit{customers}\).
Next, we enumerate the shop closing at hour \(j\) (\(1 \leq j \leq n\)). If \(\textit{customers}[j - 1]\) is 'N', it means no customer arrived during the open period, and the cost increases by \(1\); otherwise, it means a customer arrived during the closed period, and the cost decreases by \(1\). If the current cost \(\textit{cost}\) is less than the minimum cost \(\textit{mn}\), we update the answer variable \(\textit{ans}\) to \(j\), and update the minimum cost \(\textit{mn}\) to the current cost \(\textit{cost}\).
After the traversal ends, we return the answer variable \(\textit{ans}\).
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{customers}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |