[LeetCode] Minimum Penalty for a Shop

2483. Minimum Penalty for a Shop

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 come at the ith hour.

If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:

  • For every hour when the shop is open and no customers come, the penalty increases by 1.
  • For every hour when the shop is closed and customers come, the penalty increases by 1.

Return the earliest hour at which the shop must be closed to incur a minimum penalty.

Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int bestClosingTime(string s) {
int come = count(begin(s), end(s), 'Y'), none = s.length() - come;
int pass = 0;
int score = none, time = s.length();
for(int i = 0; i <= s.length(); i++) {
int now = come + pass;
if(score == now) time = min(time, i);
else if(score > now) {
score = now;
time = i;
}
if(i != s.length()) {
if(s[i] == 'N') pass += 1;
else come -= 1;
}
}
return time;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/26/PS/LeetCode/minimum-penalty-for-a-shop/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.