题目链接
Leetcode.1475 商品折扣后的最终价格 Rating : 1212
题目描述
给你一个数组 p r i c e s prices prices ,其中 p r i c e s [ i ] prices[i] prices[i] 是商店里第 i 件商品的价格。
商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 p r i c e s [ j ] prices[j] prices[j] 相等的折扣,其中 j 是满足 j > i j > i j>i 且 p r i c e s [ j ] < = p r i c e s [ i ] prices[j] <= prices[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 < = p r i c e s . l e n g t h < = 500 1 <= prices.length <= 500 1<=prices.length<=500
- 1 < = p r i c e s [ i ] < = 1 0 3 1 <= prices[i] <= 10^3 1<=prices[i]<=103
解法一:暴力
直接暴力两重循环求解。
时间复杂度: O ( n 2 ) O(n^2) O(n2)
C++代码:
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
for(int i = 0;i < n;i++){
for(int j = i + 1;j < n;j++){
if(prices[i]>=prices[j]){
prices[i] -= prices[j];
break;
}
}
}
return prices;
}
};
解法二:单调栈
原问题就是对于每一个 p r i c e s [ i ] prices[i] prices[i] 能不能在右边找到第一个 p r i c e s [ j ] prices[j] prices[j] 使得 p r i c e s [ j ] ≤ p r i c e s [ i ] prices[j] \leq prices[i] prices[j]≤prices[i],于是物品 i i i 的价格就可以打一个折扣,变成 p r i c e s [ i ] = p r i c e s [ i ] − p r i c e s [ j ] prices[i] = prices[i] - prices[j] prices[i]=prices[i]−prices[j]。
我们可以使用 单调栈。
假设我们已经处理完 区间 [ 0 , i − 1 ] [0,i - 1] [0,i−1] 的价格了,现在要处理 p r i c e s [ i ] 。 prices[i]。 prices[i]。
如果 p r i c e s [ s t k . t o p ( ) ] > = p r i c e s [ i ] prices[stk.top()] >= prices[i] prices[stk.top()]>=prices[i],即此时 栈顶元素的价格 大于等于 p r i c e [ i ] price[i] price[i],则说明 p r i c e s [ i ] prices[i] prices[i] 就是 p r i c e s [ s t k . t o p ( ) ] prices[stk.top()] prices[stk.top()] 的折扣价格。于是 p r i c e s [ s t k . t o p ( ) ] = p r i c e s [ s t k . t o p ( ) ] − p r i c e s [ i ] prices[stk.top()] = prices[stk.top()] - prices[i] prices[stk.top()]=prices[stk.top()]−prices[i],接着再弹出栈顶元素,一直重复这个过程直到循环结束。
时间复杂度: O ( n ) O(n) O(n)
C++代码:
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
stack<int> stk;
for(int i = 0;i < n;i++){
while(!stk.empty() && prices[stk.top()] >= prices[i]){
prices[stk.top()] -= prices[i];
stk.pop();
}
stk.push(i);
}
return prices;
}
};