Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Closing at hour zero incurs one penalty for every arriving customer. Moving the closing time one hour later changes only that newly opened hour: a Y removes one missed-customer penalty, while an N adds one empty-open-hour penalty.
Approach
Count all Y characters to initialize the penalty and choose closing hour zero. Scan hours left to right, subtracting one for Y or adding one for N, thereby evaluating closing at the following hour. Update the chosen hour only when the penalty strictly decreases. This preserves the earliest hour on ties. Return the best hour, including the possibilities of never opening or remaining open for the entire string.
class Solution:
def bestClosingTime(self, customers: str) -> int:
n = len(customers)
pen = 0
for x in customers:
if x == 'Y':
pen += 1
mn = pen
res = 0
for i in range(n):
if customers[i] == 'Y':
pen -= 1
else:
pen += 1
if pen < mn:
mn = pen
res = i + 1
return resComplexity analysis
Let n = customers.length. Time: O(n) across the initial penalty count and incremental sweep. Auxiliary space: O(1).
