LeetCode 2483: Minimum Penalty for a Shop

StringPrefix Sum

Problem Description

Explanation:

To find the earliest hour at which the shop must be closed to incur a minimum penalty, we can iterate through each possible closing hour and calculate the penalty for closing the shop at that hour. We can keep track of the penalty for each hour and return the hour with the minimum penalty.

  1. Initialize a variable minPenalty to store the minimum penalty found so far.
  2. Iterate through each possible closing hour:
    • For each hour, calculate the penalty by iterating through the customer log and adding 1 to the penalty for each hour where the shop is open and no customers come, or where the shop is closed and customers come.
    • Update minPenalty if the current penalty is less than the minimum penalty found so far.
  3. Return the earliest hour at which the minimum penalty occurs.

Time Complexity:

The time complexity of this approach is O(n^2) where n is the length of the customer log.

Space Complexity:

The space complexity is O(1) as we are using constant extra space.

Solutions

class Solution {
    public int minPenalty(String customers) {
        int n = customers.length();
        int minPenalty = Integer.MAX_VALUE;

        for (int i = 0; i <= n; i++) {
            int penalty = 0;
            for (int j = 0; j < n; j++) {
                if ((i <= j && customers.charAt(j) == 'Y') || (i > j && customers.charAt(j) == 'N')) {
                    penalty++;
                }
            }
            minPenalty = Math.min(minPenalty, penalty);
        }

        return minPenalty;
    }
}

Loading editor...