Minimum Penalty for a Shop - Problem
You're a shop owner analyzing the optimal closing time to minimize financial penalties. Given a string customers representing hourly customer activity:
- 'Y' at position
imeans customers visited during houri - 'N' at position
imeans no customers came during houri
If you close at hour j (meaning the shop is closed starting from hour j), you incur penalties:
- +1 penalty for each hour you're open with no customers ('N')
- +1 penalty for each hour you're closed when customers come ('Y')
Goal: Find the earliest hour to close that results in the minimum total penalty.
Example: For "YYNY", closing at hour 2 means you're open during hours 0,1 (penalty for hour 1's 'N') and closed during hours 2,3 (penalty for hour 3's 'Y'), giving total penalty = 2.
Input & Output
example_1.py โ Basic Case
$
Input:
customers = "YYNY"
โบ
Output:
2
๐ก Note:
Closing at hour 2 means: open during hours 0,1 (penalty=1 for 'N' at hour 1), closed during hours 2,3 (penalty=1 for 'Y' at hour 3). Total penalty = 2, which is minimum.
example_2.py โ No Customers
$
Input:
customers = "NNNNN"
โบ
Output:
0
๐ก Note:
Since no customers come at any hour, it's best to close immediately at hour 0 to avoid penalties for staying open with no customers. Penalty = 0.
example_3.py โ Always Customers
$
Input:
customers = "YYYY"
โบ
Output:
4
๐ก Note:
Since customers come every hour, it's best to stay open all day and close at hour 4. Any earlier closing would incur penalties for missing customers.
Constraints
- 1 โค customers.length โค 105
- customers consists only of characters 'Y' and 'N'
- The shop can close at any hour from 0 to n (inclusive)
Visualization
Tap to expand
Understanding the Visualization
1
Count missed customers
Start with penalty = total 'Y's (closing immediately)
2
Serve customers incrementally
For each 'Y' we serve by staying open, penalty decreases
3
Pay for empty hours
For each 'N' hour we stay open, penalty increases
4
Find the sweet spot
Return the earliest hour with minimum total penalty
Key Takeaway
๐ฏ Key Insight: Instead of recalculating penalties from scratch, track how the penalty *changes* as you shift closing time. Each customer served reduces penalty by 1, each empty hour endured increases it by 1.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code