【題目】1475. 商品折扣後的最終價格
給你一個數組 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】暴力法
class Solution {
public int[] finalPrices(int[] prices) {
int len = prices.length;
int[] ans = new int[len];
for(int i = 0; i < len - 1; i++){
ans[i] = prices[i];
for(int j = i + 1; j < len; j++){
if(prices[j] <= prices[i]){
ans[i] = prices[i] - prices[j];
break;
}
}
}
ans[len - 1] = prices[len - 1];
return ans;
}
}
【解題思路2】單調棧
維護一個自棧底至棧頂的嚴格單調遞增的棧
class Solution {
public int[] finalPrices(int[] prices) {
int len = prices.length;
Stack<Integer> stack = new Stack<>(); //維護一個單調遞增的棧
for(int i = 0; i < len; i++){
//棧非空,當前元素<=棧頂元素時棧頂元素出棧,當前元素就是比棧頂元素小的第一個元素
while(!stack.isEmpty() && prices[i] <= prices[stack.peek()]){
prices[stack.pop()] -= prices[i]; //出棧元素並更新
}
stack.push(i);
}
return prices;
}
}