LeetCode每日一题——1475. 商品折扣后的最终价格

简介: 给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。

题目

给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。

商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > i 且 prices[j] <= prices[i] 的 最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。

请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。

示例

示例 1:

输入:prices = [8,4,6,2,3]

输出:[4,2,4,2,3]

解释: 商品 0 的价格为 price[0]=8 ,你将得到prices[1]=4 的折扣,所以最终价格为 8 - 4 = 4 。 商品 1 的价格为 price[1]=4 ,你将得到 prices[3]=2 的折扣,所以最终价格为 4 - 2 = 2 。 商品 2 的价格为 price[2]=6 ,你将得到prices[3]=2 的折扣,所以最终价格为 6 - 2 = 4 。 商品 3 和 4 都没有折扣。

示例 2:

输入:prices = [1,2,3,4,5]

输出:[1,2,3,4,5]

解释:在这个例子中,所有商品都没有折扣。

示例 3:

输入:prices = [10,1,1,6]

输出:[9,0,1,6]

提示:

1 <= prices.length <= 500

1 <= prices[i] <= 10^3

思路

  1. 暴力:第一个for遍历原数组,第二个for自第一个for确定的元素往后寻找,找到第一个小于等于该确定元素即停,改变该确定元素值为二者的差即可。
  2. 单调栈:逆序遍历,单调栈维持栈顶最大元素即可

题解

暴力

class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        for i in range(len(prices)):
            for j in range(i+1, len(prices)):
                if prices[i] >= prices[j]:
                    prices[i] -= prices[j]
                    break
        return prices

单调栈

class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        n=len(prices)
        res=[0]*n
        stack=[]#栈 单调增
        for i in range(n-1,-1,-1):
            while stack and stack[-1]>prices[i]:
                stack.pop()
            res[i]=prices[i]-(stack[-1] if stack else 0)
            stack.append(prices[i])
        return res
目录
相关文章
|
3月前
leetcode-SQL-1795. 每个产品在不同商店的价格
leetcode-SQL-1795. 每个产品在不同商店的价格
32 0
|
21天前
|
算法
每日一题:LeetCode-LCR 179. 查找总价格为目标值的两个商品
每日一题:LeetCode-LCR 179. 查找总价格为目标值的两个商品
|
3月前
leetcode-1475:商品折扣后的最终价格
leetcode-1475:商品折扣后的最终价格
28 0
|
3月前
leetcode-zj-future04:门店商品调配
leetcode-zj-future04:门店商品调配
16 0
|
3月前
|
SQL
leetcode-SQL-1549. 每件商品的最新订单
leetcode-SQL-1549. 每件商品的最新订单
20 0
|
6月前
【Leetcode -1475.商品折扣后的最终价格 -1544.整理字符串】
【Leetcode -1475.商品折扣后的最终价格 -1544.整理字符串】
29 0
|
存储 测试技术
LeetCode每日一题——901. 股票价格跨度
编写一个 StockSpanner 类,它收集某些股票的每日报价,并返回该股票当日价格的跨度。
59 0
|
数据库
LeetCode(数据库)- 每个产品在不同商店的价格
LeetCode(数据库)- 每个产品在不同商店的价格
90 0
|
数据库
LeetCode(数据库)- 每家商店的产品价格
LeetCode(数据库)- 每家商店的产品价格
88 0
|
数据库
LeetCode(数据库)- 每位顾客最经常订购的商品
LeetCode(数据库)- 每位顾客最经常订购的商品
95 0