Algorithm/NeetCode

Minimum Penalty for a Shop

Tony Lim 2024. 11. 17. 13:21
728x90

https://leetcode.com/problems/minimum-penalty-for-a-shop/description/

class Solution:
    def bestClosingTime(self, customers: str) -> int:
        n = len(customers)

        prefix_n = [0] * (n + 1)
        postfix_y = [0] * (n + 1)

        for i in range(1, n + 1):
            prefix_n[i] = prefix_n[i-1]
            if customers[i-1] == "N":
                prefix_n[i] += 1

        for i in range(n - 1, -1, -1):
            postfix_y[i] = postfix_y[i+1]
            if customers[i] == "Y":
                postfix_y[i] += 1

        min_penalty, indx = float("inf"), 0

        for i in range(n+1):
            penalty = prefix_n[i] + postfix_y[i]
            if penalty < min_penalty:
                min_penalty = penalty
                idx = i

        return idx

prefix_n for counting "N" before pointer, because when you close at certain pointer then penatly is # of "N".

postfix_y is opposite but including certain pointer and coutn #of "Y" , because of penalty

at the end add up those prefix, postfix to count total penalty and find minimum

 

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

Majority Element II  (0) 2024.11.19
Champagne Tower  (0) 2024.11.18
Design Underground System  (0) 2024.11.15
Optimal Partition of String  (0) 2024.11.14
Number of Zero-Filled Subarrays  (0) 2024.11.13