Skip to main content
Back to problems
#2483
Medium Algorithms

Minimum penalty for a shop

String Prefix Sum
71.2% acceptance
Feb 25, 2026
2450
136
You are given the customer visit log string customers of 'N' and 'Y'. If the shop closes at the jth hour, penalty = (N's before j) + (Y's at or after j). Return the earliest closing time with minimum penalty.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn best_closing_time(customers: String) -> i32 {
    let c = customers.as_bytes();
    let total_y = c.iter().filter(|&&b| b == b'Y').count() as i32;
    let mut best_pen = total_y; // penalty at j=0: all Y's are after
    let mut best_j = 0i32;
    let mut prefix_y = 0i32;
    let mut prefix_n = 0i32;
    for (i, &b) in c.iter().enumerate() {
      if b == b'Y' { prefix_y += 1; } else { prefix_n += 1; }
      let pen = (total_y - prefix_y) + prefix_n;
      if pen < best_pen {
        best_pen = pen;
        best_j = (i + 1) as i32;
      }
    }
    best_j
  }
}