Leetcode Question Link

Analysis

Offset

The target is to find the time to achieve the smallest penalty, but not the penalty value itself. So the concrete value of penalty is not important, we could just focus on how penalty changes when changing shop closing time.

Let offset be the penalty diff when choosing closing time and closing time , that is:

Moving Closing Time

Now let’s find how changes when .


When , based on definition of offset, we have


When we moving closing time from to , discuss:

When at hour, there IS customers arriving. In this case, before moving closing time, there is an in closing time, after moving, the has been moved into open time. So actually decrease by after moving.

When at hour, there IS NOT customers arriving. by similar analysis method, we know there is an moved from closing time to opening time, increase by .

Code Implementation

class Solution {
public:
    int bestClosingTime(string customers) {
        
        // init offset
        // at time 0, offset = 0
        int offset = 0, minOffset = 0;
        unsigned minTime = 0;
        bool arrived;
        
        int rangeEnd = customers.size() + 1;
        for (int i = 1; i < rangeEnd; ++i) {
        
            // check if there is customers arrived at previous time
            arrived = (customers[i - 1] == 'Y' ? 1 : 0);
            
            // someone arrived, then moving closing time
            // 1 hour later will cause offset decreasing by 1, 
            // otherwise, offset increasing by 1
            if (arrived)
                --offset;
            else
                ++offset;
 
            // update minOffset and minTime
            if (offset < minOffset) {
                minOffset = offset;
                minTime = i;
            }
        }
 
        return minTime;
    }
};