⚡Flashcard Drill➔
NeetCode #140LC-2483MediumArrays & Hashing
← Back to All Problems

#140 · #2483 · Minimum Penalty for a Shop(商店的最少代价)

📌 Problem Statement & Constraints

A shop owner wants to choose an hour i to close, so that the penalty is minimised. The penalty is the number of 'N' customers before or at hour i plus the number of 'Y' customers after hour i. Given the string customers, return the earliest hour that minimises the penalty. Constraints: 1 <= customers.length <= 10^5.

💡 Core Algorithmic Approaches

  1. Track the penalty incrementally rather than recomputing prefix and suffix counts.
  2. Start with the penalty of closing before hour 0: it equals the total number of 'Y'.
  3. Moving the closing hour past index i changes the penalty by -1 if customers[i] == 'Y' (one fewer 'Y' remains after) and +1 otherwise (one more 'N' is now included).
  4. Record the first index achieving the minimum, which gives the earliest hour on ties.

💻 Benchmark Python3 Implementation

class Solution:
    def bestClosingTime(self, customers: str) -> int:
        penalty = customers.count("Y")     # penalty of closing before hour 0
        best = penalty
        res = 0
        for i, ch in enumerate(customers):
            penalty += -1 if ch == "Y" else 1   # moving the closing hour past i
            if penalty < best:             # strict '<' keeps the earliest hour
                best = penalty
                res = i + 1
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass after counting the Ys.
💾 Space Complexity
O(1): two counters.

⚠️ Interview Pitfalls & Follow-ups

  • Using <= when updating the best: that would keep the latest hour on ties, but the problem asks for the earliest.
  • Forgetting the initial state (closing before hour 0): it is a valid choice and must be considered.
  • Recomputing prefix and suffix arrays for every candidate hour: O(n^2). The incremental update is O(1) per step.
  • Returning the index i instead of i + 1: the hour refers to the number of hours open, so closing after index i means hour i + 1.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

商店的最少代价

给你一个顾客访问商店的日志,用一个下标从 0 开始且只包含字符 N 和 Y 的字符串 customers 表示: customers[i] = "Y" 表示第 i 小时有顾客到达, customers[i] = "N" 表示没有顾客到达。商店老板可以在某个小时关门,从该小时开始商店不再营业。如果在第 j 小时关门,那么 代价 是「在关门前(0 到 j−1)没有顾客的小时数」加上「关门后(j 到 n−1)有顾客的小时数」。请你返回 最小代价 对应的 最早 关门时间 j。约束:1 ≤ customers.length ≤ 10^5;customers[i] 为 N 或 Y。

核心要点

  • 增量维护代价(标准解) :设 j = 0 时的代价为「字符串中 Y 的总数」(关门前无小时,关门后全部 Y 都损失)。
  • 从 j 推到 j+1 :第 j 小时从「关门后」变为「关门前」。若 customers[j] == "Y" ,则它不再计入损失,代价减 1;若为 "N" ,则它变成「关门前没有顾客的小时」,代价加 1。
  • 求最小且最早 :用严格小于 &lt; 更新,保证并列时保留 最早 的 j。
  • 枚举范围 :j 从 0 到 n(共 n + 1 种关门时刻,包括「从不营业」和「一直营业」)。

常见陷阱

  • 每个候选时刻都重新统计代价 :O(n²) 会超时。必须用增量更新。
  • 更新条件写反 : Y 使代价减 1(不再损失)、 N 使代价加 1(新增无顾客小时)。写反会得到完全错误的结果。
  • 用 &lt;= 更新最优 :题目要求并列时返回 最早 的时刻,因此必须用严格小于 &lt; 。
  • 忘记 j 可以取到 n :关门时刻可以是 n(表示一直营业),因此循环需要遍历全部 n 个小时并把 j 递增到 n。

参考实现

class Solution:
    def bestClosingTime(self, customers: str) -> int:
        # j = 0 时的代价:关门后(整个字符串)有顾客的小时数
        penalty = customers.count('Y')
        best = penalty
        best_hour = 0
        for j, c in enumerate(customers, start=1):
            # 第 j-1 小时由「关门后」变为「关门前」
            if c == 'Y':
                penalty -= 1        # 少了一个损失的顾客小时
            else:
                penalty += 1        # 多了一个「关门前无顾客」的小时
            if penalty < best:      # 严格小于 -> 并列时保留更早的
                best = penalty
                best_hour = j
        return best_hour