Minimum Penalty for a Shop

medium prefix sum sweep

Problem

A shop's day is described by a string customers of length n, where the i-th character is 'Y' if customers show up during hour i and 'N' if nobody does. You may close the shop at any hour j from 0 to n: hours 0..j−1 are open and hours j..n−1 are closed.

The penalty for closing at hour j is the number of open hours with no customers plus the number of closed hours when customers arrive. Return the earliest closing hour with the minimum penalty.

Inputcustomers = "YYNY"
Output2
Closing at hour 2 serves both 'Y' hours 0 and 1 and only misses the customers at hour 3, for a minimum penalty of 1.

def best_closing_time(customers):
    penalty = customers.count("Y")    # close at hour 0
    best = penalty
    best_hour = 0
    for j, ch in enumerate(customers):
        if ch == "N":
            penalty += 1    # one more empty open hour
        else:
            penalty -= 1    # one less missed customer
        if penalty < best:
            best = penalty
            best_hour = j + 1
    return best_hour
function bestClosingTime(customers) {
  let penalty = 0;
  for (const ch of customers) if (ch === "Y") penalty++;
  let best = penalty, bestHour = 0;
  for (let j = 0; j < customers.length; j++) {
    penalty += customers[j] === "N" ? 1 : -1;
    if (penalty < best) {
      best = penalty;
      bestHour = j + 1;
    }
  }
  return bestHour;
}
int bestClosingTime(String customers) {
    int penalty = 0;
    for (char ch : customers.toCharArray()) if (ch == 'Y') penalty++;
    int best = penalty, bestHour = 0;
    for (int j = 0; j < customers.length(); j++) {
        penalty += customers.charAt(j) == 'N' ? 1 : -1;
        if (penalty < best) {
            best = penalty;
            bestHour = j + 1;
        }
    }
    return bestHour;
}
int bestClosingTime(string customers) {
    int penalty = 0;
    for (char ch : customers) if (ch == 'Y') penalty++;
    int best = penalty, bestHour = 0;
    for (int j = 0; j < (int)customers.size(); j++) {
        penalty += customers[j] == 'N' ? 1 : -1;
        if (penalty < best) {
            best = penalty;
            bestHour = j + 1;
        }
    }
    return bestHour;
}
Time: O(n) Space: O(1)