Leetcode 2483: Minimum Penalty for a Shop

grid47
grid47
Exploring patterns and algorithms
Mar 3, 2024 7 min read

You are given a string representing the log of a shop’s customer visits over a series of hours. Each character in the string is either ‘Y’ (customer visits) or ‘N’ (no customer visits). The shop can close at any given hour, and the penalty is determined by two factors: when the shop is open but no customers visit, and when the shop is closed but customers still arrive. You need to determine the earliest hour at which the shop should close to minimize the penalty.
Problem
Approach
Steps
Complexity
Input: A string customers of length n, consisting of characters 'Y' and 'N', representing customer visits during each hour.
Example: customers = "YYNY"
Constraints:
• 1 <= customers.length <= 10^5
• customers consists only of characters 'Y' and 'N'.
Output: The earliest hour at which the shop should close to incur the minimum penalty.
Example: Output: 2
Constraints:
• The returned value will be an integer between 0 and the length of the customers string.
Goal: Find the earliest hour to close the shop such that the penalty is minimized.
Steps:
• Count the number of 'N' characters (hours with no customers) and 'Y' characters (hours with customers).
• Calculate the penalty for closing the shop at each hour, considering both the hours open without customers and the hours closed with customers.
• Return the earliest hour that results in the least penalty.
Goal: The length of the customers string is at most 10^5, so an efficient solution is required.
Steps:
• 1 <= customers.length <= 10^5
• customers consists only of characters 'Y' and 'N'.
Assumptions:
• The penalty is computed by considering both the shop's open and closed hours relative to customer visits.
Input: customers = "YYNY"
Explanation: When closing the shop at hour 0, the penalty is 3 (1 hour of no customers while open, 1 hour of customers while closed). Closing at hour 2 results in the lowest penalty of 1, which is the optimal time to close.

Input: customers = "NNNNN"
Explanation: Since no customers visit, the best time to close is immediately at hour 0 to avoid any penalties.

Input: customers = "YYYY"
Explanation: In this case, the best time to close the shop is at hour 4, since there are customers at every hour.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus