Medium
You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
ith character is 'Y', it means that customers come at the ith hour'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:
1.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.
Example 1:
Input: customers = “YYNY”
Output: 2
Explanation:
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
Example 2:
Input: customers = “NNNNN”
Output: 0
Explanation: It is best to close the shop at the 0th hour as no customers arrive.
Example 3:
Input: customers = “YYYY”
Output: 4
Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 105customers consists only of characters 'Y' and 'N'.public class Solution {
public int bestClosingTime(String customers) {
int[] yes = new int[customers.length() + 1];
int[] no = new int[customers.length() + 1];
int count = 0;
for (int i = customers.length() - 1; i >= 0; i--) {
if (customers.charAt(i) == 'Y') {
count++;
}
yes[i] = count;
}
count = 0;
for (int i = 0; i < customers.length(); i++) {
if (customers.charAt(i) == 'N') {
count++;
}
no[i + 1] = count;
}
int min = Integer.MAX_VALUE;
int res = 0;
for (int i = 0; i < yes.length; i++) {
int sum = yes[i] + no[i];
if (min > sum) {
min = sum;
res = i;
}
}
return res;
}
}