Leetcode 1475. Final Prices With a Special Discount in a Shop
Given a list of prices for a shop, you need to compute the final prices after applying a special discount. The discount on the price of a particular item is equal to the price of the next item in the list which has a price less than or equal to the current item’s price. If there is no such item, then no discount is applied to the current item’s price.
Write a function vector<int> finalPrices(vector<int>& prices)
that takes a list of integers prices
where prices[i]
is the price of the i-th
item, and returns a list of integers representing the final prices after the discounts have been applied.
We can use a stack to efficiently find the next smaller or equal price to the right for each item. This allows us to solve the problem in linear time complexity.
#include <vector>
#include <stack>
std::vector<int> finalPrices(std::vector<int>& prices) {
int n = prices.size();
std::vector<int> result(prices);
std::stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && prices[st.top()] >= prices[i]) {
int idx = st.top();
st.pop();
result[idx] = prices[idx] - prices[i];
}
st.push(i);
}
return result;
}
result
vector is initialized with the same elements as prices
.st
is used to keep track of indices where we are looking for a discount.prices
vector.prices[i]
).result
at that index by prices[i]
.i
onto the stack.result
vector as the final prices after discount application.This approach efficiently computes the final prices after applying the described discounts.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?