[LeetCode] Final Prices With a Special Discount in a Shop

1475. Final Prices With a Special Discount in a Shop

You are given an integer array prices where prices[i] is the price of the ith item in a shop.

There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.

Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
vector<int> st, res(prices.size());
for(int i = prices.size() - 1; i >= 0; i--) {
while(st.size() and prices[st.back()] > prices[i]) st.pop_back();
res[i] = prices[i] - (st.size() ? prices[st.back()] : 0);
st.push_back(i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/18/PS/LeetCode/final-prices-with-a-special-discount-in-a-shop/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.