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 of n letters. The letter at position i is 'Y' if customers came in hour i, and 'N' if nobody came. Hours are numbered from 0. If the shop closes at hour j, where j is any number from 0 to n, it is open for hours 0 to j - 1 and closed from hour j on.

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
Input: customers = "YYNY"
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
Input: customers = "NNNNN"
Output: 0
Example 3
Input: customers = "YYYY"
Output: 4
Solution

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" from Example 1. It has four hours, so there are five closing hours to choose from, 0 to 4. Closing at 0 means the shop never opens, and the three 'Y' hours turn customers away: penalty 3. Closing at 2 keeps hours 0 and 1 open, and both had customers, which is fine. Hour 2 is closed but had nobody, also fine. Only hour 3, closed with customers, counts: penalty 1. Closing at 4 keeps every hour open, and only the empty hour 2 counts: penalty 1 again.

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 log YYNY as four hours. Closing at hours 0 to 4 gives penalties 3, 2, 1, 2 and 1. Each step to a later closing hour changes the penalty by -1 for a Y hour and +1 for an N hour. Closing at 2 is the earliest hour with the lowest penalty.

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 change starts at 0 and gets -1 or +1 per hour. The lowest change sits at the same closing hour as the lowest penalty, and the counting pass is not needed.

Remembering the lowest point

How do we know where the lowest point was once the walk is over? Two more variables keep it: lowest, the smallest change seen so far, and bestHour, the closing hour where it was seen. After reading hour i, the shop's hours 0 to i are open, so change belongs to closing at hour i + 1.

Both start at 0, which stands for closing at hour 0 before any hour is read. That start matters for a log like "NNNNN": there change only goes up, never below 0, and closing at 0 stays the answer.

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 bestHour only when change is strictly lower than lowest. A later hour with the same value leaves the earlier one in place.

Java Solution

The method bestClosingTime works in these steps:

  1. First, set three variables to 0: change for the running sum, lowest for its smallest value so far, and bestHour for the closing hour where that value was seen. All three describe closing at hour 0.
  2. Walk through the log with a loop, where i is the hour being read. Add -1 to change if hour i is 'Y', and +1 if it is 'N'. change now belongs to closing at hour i + 1.
  3. If change is strictly lower than lowest, store it in lowest and set bestHour to i + 1.
  4. When the loop is done, return bestHour.

The main method runs the three examples, a log with a tie, two logs of a single hour, and a log whose penalty first rises and only later falls.

Java
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:

Output
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", closing at hours 0 to 4 gives penalties 2, 1, 2, 1 and 2, so hours 1 and 3 tie, and the strict < keeps hour 1. With <= instead, the method returns 3 here, and 4 for "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", the first hour is empty, so change rises to 1 before it ever falls. The loop keeps going, and closing at hour 4 still turns out best, with a penalty of 2 against 4 for closing at 0.

The original implementation, MinimumPenaltyForAShop.java, is on GitHub.

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 customers. The loop reads each letter once and does one addition and one comparison for it.
  • Space: O(1). The method keeps only three numbers, change, lowest and bestHour, however long the log is. It never stores the penalties themselves.

Keeping track of the lowest point while walking through an array is also the heart of Best Time to Buy and Sell Stock.