1475. Final Prices With a Special Discount in a Shop

Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.

Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.

n2方法,两层for循环,对于每个i去寻找最小的j满足prices[j] <= prices[i],然后prices[i] -= prices[j]就是答案了

on方法,维护一个单调上升的栈,遇到比栈顶更小的值的时候,就是找到最小j的时候,把栈里比price[j]价格高的都出栈,然后都分别减去这个prices[j] ,就得到了他们的最终结果,再把j入栈。重复这个过程

class Solution(object):
    def finalPrices(self, prices):
        """
        :type prices: List[int]
        :rtype: List[int]
        """
        stack = []
        for i in range(len(prices)):
            while len(stack) != 0 and prices[stack[-1]] >= prices[i]:
                prices[stack[-1]] -= prices[i]
                stack.pop()
            stack.append(i)
        return prices
                
原文地址:https://www.cnblogs.com/whatyouthink/p/13207231.html