Sponsored
Sponsored
This approach involves preprocessing the input string to obtain counts of 'Y' before each hour and 'N' from each hour to the end. This allows us to quickly calculate the penalty for closing the shop at any given hour.
Time Complexity: O(n)
Space Complexity: O(n)
1using System;
2
3class Program {
4 public static int MinimumPenalty(string customers) {
5 int n = customers.Length;
6 int[] yPrefix = new int[n + 1];
7 int[] nSuffix = new int[n + 1];
8
9 for (int i = 0; i < n; i++) {
10 yPrefix[i + 1] = yPrefix[i] + (customers[i] == 'Y' ? 1 : 0);
11 }
12
13 for (int i = n - 1; i >= 0; i--) {
14 nSuffix[i] = nSuffix[i + 1] + (customers[i] == 'N' ? 1 : 0);
15 }
16
17 int minPenalty = n;
18 int minHour = 0;
19 for (int j = 0; j <= n; j++) {
20 int penalty = yPrefix[j] + nSuffix[j];
21 if (penalty < minPenalty) {
22 minPenalty = penalty;
23 minHour = j;
24 }
25 }
26
27 return minHour;
28 }
29
30 static void Main() {
31 string customers = "YYNY";
32 int result = MinimumPenalty(customers);
33 Console.WriteLine(result);
34 }
35}
The program leverages cumulative arrays to efficiently evaluate penalties using preprocessed summations of potential penalties for different closing times, offering rapid results determination.
This implementation uses two counters: 'open_no_customers' for open hours without customers and 'closed_with_customers' for closed hours with customers. As we evaluate each closing hour, penalties are adjusted efficiently without needing full array storage.