Minimum Penalty for a Shop
Find the earliest hour to close a shop so that empty open hours and missed customers add up to the least.
You are given a shop's customer log for one day as a string customers
The penalty for closing at hour j is the number of open hours with no customers, plus the number of closed hours in which customers came. Return the earliest closing hour with the lowest penalty.
Example 1
Output: 2
Explanation: closing at hours 0 to 4 gives penalties 3, 2, 1, 2 and 1. Hours 2 and 4 both give 1, and 2 is earlier.
Example 2
Output: 0
Example 3
Output: 4
The Idea
Picture a shopkeeper looking back over yesterday's log and asking when it would have been best to close. Staying open through a quiet hour wastes that hour. Closing too early turns customers away. The penalty counts both kinds of bad hour, and we want the closing hour where it is smallest.
Take the log "YYNY"
Working out each penalty like this means reading the whole log once for every closing hour. Is there a quicker way? Compare closing at one hour with closing an hour later. Every hour stays the same except one, which changes from closed to open. Look at the picture below.
The top row is the log, one box per hour. The dashed lines between the boxes are the closing hours, and the box under each line holds the penalty for closing there. Going from "close at 0" to "close at 1" opens hour 0. Hour 0 is 'Y', so its customers are now served, and the penalty drops by 1, from 3 to 2. Going from "close at 2" to "close at 3" opens hour 2, which is 'N'. That adds one empty open hour, and the penalty rises by 1, from 1 to 2.
So we never have to count a penalty from scratch. Starting from the penalty for closing at 0, we walk through the log once and add -1 for each 'Y' and +1 for each 'N'. A total that is updated step by step like this is called a running sum. The answer is the place where the running sum is lowest, taking the earlier place when two are equally low, like "close at 2" and "close at 4" in the picture.
Solution Approach
Turning that idea into code means settling three things: how to count the penalties, how to remember where the penalty is lowest, and which closing hour wins a tie.
Counting the penalties
Why not simply compute every penalty from scratch? For a log of n hours there are n + 1 closing hours, and each one needs a pass over all n letters. That is about n² steps: a million steps for a log of 1,000 hours, where the running sum needs about 1,000.
The penalty for closing at 0 is the number of 'Y' letters, so the running sum could start there, after one counting pass. But we only need to know where the penalty is lowest, not how big it is. Every penalty is the penalty for closing at 0 plus the changes since, so we can track only the changes. A variable changechange
Remembering the lowest point
How do we know where the lowest point was once the walk is over? Two more variables keep it: lowestchangebestHourchange
Both start at 0, which stands for closing at hour 0 before any hour is read. That start matters for a log like "NNNNN"change
Breaking ties
Which hour wins when two penalties are equally low? The problem asks for the earliest one. The walk meets closing hours from early to late, so it is enough to replace bestHourchangelowest
Java Solution
The method bestClosingTime
- First, set three variables to 0:
for the running sum,change for its smallest value so far, andlowest for the closing hour where that value was seen. All three describe closing at hour 0.bestHour - Walk through the log with a loop, where
is the hour being read. Add -1 toi if hour i is 'Y', and +1 if it is 'N'.change now belongs to closing at hour i + 1.change - If
is strictly lower thanchange , store it inlowest and setlowest to i + 1.bestHour - When the loop is done, return
.bestHour
The main
public class MinimumPenaltyForAShop {
public static int bestClosingTime(String customers) {
int change = 0; // penalty(closing at i + 1) - penalty(closing at 0)
int lowest = 0; // the lowest change seen so far
int bestHour = 0; // the earliest closing hour with that lowest change
for (int i = 0; i < customers.length(); i++) {
change += customers.charAt(i) == 'Y' ? -1 : 1;
if (change < lowest) { // strictly lower: on a tie, keep the earlier hour
lowest = change;
bestHour = i + 1;
}
}
return bestHour;
}
public static void main(String[] args) {
String[] logs = {"YYNY", "NNNNN", "YYYY", "YNYN", "N", "Y", "NYYYNY"};
for (String customers : logs) {
System.out.println(customers + " -> close at hour " + bestClosingTime(customers));
}
}
}
Running it prints:
YYNY -> close at hour 2
NNNNN -> close at hour 0
YYYY -> close at hour 4
YNYN -> close at hour 1
N -> close at hour 0
Y -> close at hour 1
NYYYNY -> close at hour 4
The first three lines give hours 2, 0 and 4, the answers to the three examples. Look at the fourth line. For "YNYN"<<="YYNY"
The two single-hour logs show both ends of the range: an empty hour is best skipped, so the shop closes at 0, and a busy hour is best kept open, so it closes at 1. In the last line, "NYYYNY"change
The original implementation,
Complexity
The work is a single walk through the log, with a fixed amount of work per hour.
- Time: O(n), where n is the length of
. The loop reads each letter once and does one addition and one comparison for it.customers - Space: O(1). The method keeps only three numbers,
,change andlowest , however long the log is. It never stores the penalties themselves.bestHour
Keeping track of the lowest point while walking through an array is also the heart of