Skip to content

Commit fc16d01

Browse files
Merge pull request neetcode-gh#2932 from Abe0770/main
Create 2483-minimum-penalty-for-a-shop.cpp
2 parents 260b655 + fe87ad9 commit fc16d01

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
3+
if the ith character is 'Y', it means that customers come at the ith hour
4+
whereas 'N' indicates that no customers come at the ith hour.
5+
6+
If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
7+
For every hour when the shop is open and no customers come, the penalty increases by 1.
8+
For every hour when the shop is closed and customers come, the penalty increases by 1.
9+
10+
Return the earliest hour at which the shop must be closed to incur a minimum penalty.
11+
Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
12+
13+
Ex. Input: customers = "YYNY"
14+
Output: 2
15+
Explanation:
16+
- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
17+
- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
18+
- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
19+
- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
20+
- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
21+
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
22+
23+
Time : O(N)
24+
Space : O(1)
25+
*/
26+
27+
class Solution {
28+
public:
29+
int bestClosingTime(string customers) {
30+
int res = -1, maxi = 0, pen = 0;
31+
for(int i = 0 ; i < customers.size() ; ++i) {
32+
if(customers[i] == 'Y')
33+
++pen;
34+
else
35+
--pen;
36+
if(pen > maxi) {
37+
maxi = pen;
38+
res = i;
39+
}
40+
}
41+
return ++res;
42+
}
43+
};

0 commit comments

Comments
 (0)