Skip to content

1475. 商品折扣后的最终价格

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

商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > iprices[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

解答

prices[i] 右侧第一个小于等于它的数。

  • 从右往左遍历,栈顶最大,栈底最小,栈底到栈顶递增
  • 如果当前数小于栈顶,弹出栈顶(栈顶元素不会成为答案)

代码

C++ 代码

cpp
class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        int n = prices.size();

        vector<int> ans(n);
        stack<int> stk;

        for (int i = n - 1; i >= 0; i --) {
            while (!stk.empty() && stk.top() > prices[i]) {
                stk.pop();
            }

            ans[i] = stk.empty() ? prices[i] : prices[i] - stk.top();

            stk.emplace(prices[i]);
        }

        return ans;
    }
};

Python 代码

python
class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        n = len(prices)
        ans = [0] * n
        stk = []

        for i in range(n - 1, -1, -1):
            while len(stk) > 0 and stk[-1] > prices[i]:
                stk.pop()
            
            tmp = 0 if len(stk) <= 0 else stk[-1]

            ans[i] = prices[i] - tmp

            stk.append(prices[i])
        
        return ans

数组模拟栈

  • 从左往右遍历,出栈的时候得到答案
  • 当前元素小于栈顶元素时,说明 栈顶元素对应的答案 已经找到
cpp
class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        int n = prices.size();

        int st[n + 1], top = -1;
        
        for(int i = 0; i < n; i ++) {
            while(top != -1 && prices[st[top]] >= prices[i]) {
                int j = st[top --];
                prices[j] -= prices[i];  
            }

            st[++ top] = i;
        }

        return prices;
    }
};

Released under the MIT License.