Soohan-Kim / Leetcode

0 stars 0 forks source link

[HW 4] Final Prices With a Special Discount in a Shop #1475. #51

Open Soohan-Kim opened 4 months ago

Soohan-Kim commented 4 months ago

https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/

Soohan-Kim commented 4 months ago
class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        stack = [-1]
        ans = [prices[-1]]

        for i in range(len(prices)-2, -1, -1):

            while stack and prices[i] < prices[stack[-1]]:
                stack.pop()
            if stack:
                price = prices[i] - prices[stack[-1]] 
            else:
                price = prices[i]
            ans.insert(0, price)
            stack.append(i)

        return ans