Repository navigation
Expand file tree
/
Copy path_6250MinimumPenaltyForAShop.java
More file actions
72 lines (70 loc) · 2.58 KB
/
Copy path_6250MinimumPenaltyForAShop.java
File metadata and controls
72 lines (70 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.heatwave.leetcode.contest.biweekly._20221126_92;
/**
* 6250. 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':
* <p>
* 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:
* <p>
* 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.
* <p>
* Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
* <p>
* <p>
* <p>
* Example 1:
* <p>
* Input: customers = "YYNY"
* Output: 2
* Explanation:
* - Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
* - Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
* - Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
* - Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
* - Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
* Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
* Example 2:
* <p>
* Input: customers = "NNNNN"
* Output: 0
* Explanation: It is best to close the shop at the 0th hour as no customers arrive.
* Example 3:
* <p>
* Input: customers = "YYYY"
* Output: 4
* Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
* <p>
* <p>
* Constraints:
* <p>
* 1 <= customers.length <= 105
* customers consists only of characters 'Y' and 'N'.
*/
public class _6250MinimumPenaltyForAShop {
static class Solution {
public int bestClosingTime(String customers) {
char[] chars = customers.toCharArray();
int[] penalty = new int[chars.length];
int current = 0, max = 0;
for (int i = 0; i < chars.length; i++) {
current += chars[i] == 'Y' ? 1 : -1;
penalty[i] = current;
max = Math.max(current, max);
}
if (max == 0) {
return 0;
}
int res = 0;
for (int i = 0; i < penalty.length; i++) {
if (penalty[i] == max) {
res = i;
break;
}
}
return res + 1;
}
}
}