#2483
Minimum Penalty for a Shop
pupil · 545 · lc medium +28 · verified · 71.2% accepted · 2,451 likes · top 80%
Description
A shop's visit log is represented by a 0-indexed string customers of 'Y' and 'N' characters, where 'Y' means customers arrived that hour and 'N' means they did not. If the shop closes at hour j (0 <= j <= n), the penalty equals the number of open hours with no customers plus the number of closed hours with customers. Return the earliest closing hour that minimizes the penalty.
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.
Code
1
2
3