「每日LeetCode」2021年4月27日

本文最后更新于:2023年3月19日 晚上

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

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

给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。
商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > iprices[j] <= prices[i]最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。
请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。

示例 1:

1
2
3
4
5
6
7
输入: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:

1
2
3
输入:prices = [1,2,3,4,5]
输出:[1,2,3,4,5]
解释:在这个例子中,所有商品都没有折扣。

示例 3:

1
2
输入:prices = [10,1,1,6]
输出:[9,0,1,6]

提示:

  • 1 <= prices.length <= 500
  • 1 <= prices[i] <= 10^3

思路

很显然一个双重遍历就可以实现。

单调栈

维护一个单调递增栈,存储的是对应值的索引。遍历数组,如果栈里没有元素,则直接将当前元素的索引值加入栈中。有元素且栈顶元素比当前值大时,说明当前值就是这个下标对应的打折折扣,给结果数组对应下标赋值,并出栈,继续判断栈顶元素是否符合要求,直到栈空或者当前值比栈顶元素大。遍历完成后,剩下的都是无法打折的,直接放回原位即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {number[]} prices
* @return {number[]}
*/
var finalPrices = function (prices) {
return prices.map((price, i) => {
let target = null;
for (let j = i + 1; j < prices.length; j++) {
const element = prices[j];
if (element <= price) {
target = element;
break;
}
}
return price - (target ? target : 0);
});
};

单调栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param {number[]} prices
* @return {number[]}
*/
var finalPrices = function (prices) {
const stack = [];
const res = [];
for (let i = 0; i < prices.length; i++) {
const price = prices[i];
let pop = prices[stack[stack.length - 1]];
while (stack.length && pop >= price) {
pop = prices[stack[stack.length - 1]];
if (pop >= price) {
const index = stack.pop();
res[index] = pop - price > 0 ? pop - price : 0;
}
}
stack.push(i);
}
while (stack.length) {
const index = stack.pop();
res[index] = prices[index];
}
return res;
};