zoukankan      html  css  js  c++  java
  • 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
                    
  • 相关阅读:
    [USACO08FEB]酒店Hotel 线段树 BZOJ 1593
    有趣的数 zoj 月赛
    [ZJOI2008]生日聚会 BZOJ1037 dp
    借教室 差分+二分答案
    HackerRank
    旅行计划 记忆化搜索
    灾后重建 Floyd
    [USACO10OCT]湖计数Lake Counting 联通块
    [TJOI2013]循环格 费用流 BZOJ3171
    高斯消元
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13207231.html
Copyright © 2011-2022 走看看