Minimum Penalty for a Shop

You are given a shop's customer log as a string customers of 'Y' and 'N': customers[i] is 'Y' if customers come at hour i and 'N' if none come. If the shop closes at hour j (0 <= j <= n), every open hour with no customers costs 1 and every closed hour with customers costs 1. Return the earliest hour at which the shop should close to get the minimum penalty.

30:00

Minimum Penalty for a Shop
medium
Free written solution
Topics
Companies

You are given a shop's customer log as a string customers of 'Y' and 'N': customers[i] is 'Y' if customers come at hour i and 'N' if none come. If the shop closes at hour j (0 <= j <= n), every open hour with no customers costs 1 and every closed hour with customers costs 1. Return the earliest hour at which the shop should close to get the minimum penalty.

Example 1:
Input: {"customers":"YYNY"}
Output: 2
Constraints:
  • 1≤customers.length≤1051 \leq \text{customers.length} \leq 10^5

  • customers consists only of 'Y' and 'N'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"customers":"YYNY"}

Closing at hour 0 means every 'Y' hour is missed, a penalty of 3. Track the penalty relative to that, starting at 0, and slide the closing time right one hour at a time.

closing at hour 0 · open 0 h, closed 4 h

Y

miss

Y

miss

N

2

Y

miss

open with no customers: 0
closed with customers: 3

penalty if closing at each hour

3

penalty now

3

3 + 0

best hour

0

penalty 3

Variables
VariableValue
penalty0
best0
bestHour0
DepthFunction Call
Stack empty
0/9