Minimum Penalty for a Shop - Problem
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 - If the
ithcharacter is'N', it means 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: If a shop closes at the jth hour, it means the shop is closed at the hour j.
Input & Output
Example 1 — Basic Case
$
Input:
customers = "YYNY"
›
Output:
2
💡 Note:
Closing at hour 2 gives penalty of 1: open during hours 0,1 (both Y, no penalty) and closed during hours 2,3 (one Y at hour 3, penalty=1)
Example 2 — All Customers
$
Input:
customers = "YYYY"
›
Output:
4
💡 Note:
Best to stay open all hours (close at hour 4): no penalty for being open with customers, penalty=0
Example 3 — No Customers
$
Input:
customers = "NNNN"
›
Output:
0
💡 Note:
Best to close immediately (hour 0): no penalty for being closed when no customers come, penalty=0
Constraints
- 1 ≤ customers.length ≤ 105
- customers consists only of characters 'Y' and 'N'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Customer log string with Y (customer) and N (no customer)
2
Process
Calculate penalty for each closing hour
3
Output
Earliest hour with minimum penalty
Key Takeaway
🎯 Key Insight: Penalty changes predictably as closing hour moves right: lose N penalties, gain Y penalties
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code