Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 26, 2025 18:19
Show Gist options
  • Select an option

  • Save tatsuyax25/5b1858c0179bb7dbd56fae577b6106e6 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/5b1858c0179bb7dbd56fae577b6106e6 to your computer and use it in GitHub Desktop.
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 ith character is 'Y', it means that customers come at the ith hour whereas 'N' indicates that no customers c
/**
* Given a string of 'Y' (customer arrives) and 'N' (no customer),
* find the hour to close the shop that minimizes penalty.
*
* Penalty rules:
* - Staying open while no customers come → +1 penalty for each 'N'
* - Closing early while customers would have come → +1 penalty for each 'Y'
*
* @param {string} customers
* @return {number}
*/
var bestClosingTime = function (customers) {
const n = customers.length;
// Initial penalty: assume we close at hour 0 (never open).
// That means every 'Y' is a missed customer → penalty += 1.
let penalty = 0;
for (let i = 0; i < n; i++) {
if (customers[i] === 'Y') penalty++;
}
// Track best answer: [bestHour, bestPenalty]
let best = [0, penalty];
// Sweep through each possible closing hour 1..n
for (let hour = 1; hour <= n; hour++) {
// We "move" the boundary one step to the right.
// customers[hour - 1] is now considered "open" instead of "closed".
if (customers[hour - 1] === 'Y') {
// Previously counted as a missed customer → remove penalty.
penalty--;
} else {
// Now we stay open during an 'N' → add penalty.
penalty++;
}
// Update best closing hour if penalty improves.
if (penalty < best[1]) {
best = [hour, penalty];
}
}
return best[0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment