Try   HackMD

2483.Minimum Penalty for a Shop

tags: Medium String Prefix Sum

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.

範例

Example 1:

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:

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 <= 105
  • customers consists only of characters 'Y' and 'N'.

解答

C++

class Solution { public: const int INF = 1e5 + 10; int bestClosingTime(string customers) { ios_base::sync_with_stdio(0); cin.tie(0); int numCustomers = customers.size(); vector<int> prefixN(numCustomers + 1, 0); for (int i = 1; i <= numCustomers; i ++) { prefixN[i] = prefixN[i - 1] + static_cast<int>(customers[i - 1] == 'N'); } int suffixY = 0; int minPenalty = INF, minPenaltyHour = 0; for (int ithHour = numCustomers; ithHour >= 0; ithHour --) { suffixY += static_cast<int>(customers[ithHour] == 'Y'); if (prefixN[ithHour] + suffixY <= minPenalty) { minPenalty = prefixN[ithHour] + suffixY; minPenaltyHour = ithHour; } } return minPenaltyHour; } };

Jerry Wu

C#

public class Solution { public int BestClosingTime(string customers) { int score = 0; int max = 0; int ans = 0; for (int i = 0; i < customers.Length; i++) { score = customers[i] == 'Y' ? score + 1 : score - 1; if (score > max) { max = score; ans = i + 1; } } return ans; } }

JimAug 29, 2023

Reference

回到題目列表