# 2483. Minimum Penalty for a Shop ###### tags: `Leetcode` `Medium` Link: https://leetcode.com/problems/minimum-penalty-for-a-shop/description/ ## 思路 penalty = 关之前'N'的数目+关的时候和关之后'Y'的数目 只需要从前往后遍历就可以计算出关之前'N'的数目 如果知道总共有几个'Y'-关之前遇到的'Y' 那么我们就得到了 关的时候和关之后'Y'的数目 写完code发现其实根本不需要多花O(n)算一共有多少个'Y' 我们只要直接找到noCount-customerCount最小的index即可 ## Code 优化前 ```java= class Solution { public int bestClosingTime(String customers) { int total = 0; int n = customers.length(); for(int i=0; i<n; i++){ if(customers.charAt(i)=='Y') total++; } int bestTime = 0; int minPenalty = Integer.MAX_VALUE; int noCount = 0; int customerCount = 0; for(int i=0; i<=n; i++){ int currPenalty = noCount+total-customerCount; if(currPenalty<minPenalty){ minPenalty = currPenalty; bestTime = i; } if(i==n) continue; if(customers.charAt(i)=='Y') customerCount++; else noCount++; } return bestTime; } } ``` 优化后 ```java= class Solution { public int bestClosingTime(String customers) { int n = customers.length(); int bestTime = 0; int minPenalty = Integer.MAX_VALUE; int noCount = 0; int customerCount = 0; for(int i=0; i<=n; i++){ int currPenalty = noCount-customerCount; if(currPenalty<minPenalty){ minPenalty = currPenalty; bestTime = i; } if(i==n) continue; if(customers.charAt(i)=='Y') customerCount++; else noCount++; } return bestTime; } } ```