Ctrl K

When to Close the Shop

Medium
A shop's visit log is a string visits of length n made of 'Y' and 'N': visits[i] = 'Y' if customers came during hour i, and 'N' if nobody did. The owner picks a closing hour j (0 ≤ j ≤ n): the shop is open during hours 0, …, j − 1 and closed from hour j on. The penalty is: - +1 for each hour the shop is open but no customers come; - +1 for each hour the shop is closed but customers do come. Return the earliest closing hour with the smallest penalty.
Example 1
visits="NYYNY" → 3

Closing at hour 0 costs 3: all three busy hours are lost. Closing at hour 3 costs 2: hour 0 was open and idle, and the customers of hour 4 are missed. Hour 5 also costs 2, but 3 is earlier and nothing costs less.

Example 2
visits="NNN" → 0

No customers at all, so it is best never to open: close at hour 0.

Example 3
visits="YYNYY" → 5
Constraints
  • 1 ≤ len(visits) ≤ 10⁵
  • visits consists only of 'Y' and 'N'
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRoll Letters by Prefix MediumPalindrome After a Few Fixes MediumMatching Stretch Within Budget MediumEven Vowel Stretch MediumSeparate Two Words by Letters Medium
loading Python…
Input
visits="NYYNY"
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 155 tests on the server, hidden ones included.