You have an array of prices where prices[i]
is the price of the i-th
item in a shop. There is a special discount for items in the shop: if you buy the i-th
item, then you will receive a discount equivalent to the price of the next item that is cheaper or equal than the i-th
item. If there isn’t an item that meets this criterion, you won’t get any discount for the i-th
item.
Return an array where the i-th
element is the price you need to pay for the i-th
item after a suitable discount.
Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
1 <= prices.length <= 500
1 <= prices[i] <= 10^3
To solve this problem efficiently:
def finalPrices(prices):
n = len(prices)
result = [0] * n
stack = []
for i in range(n):
while stack and prices[stack[-1]] >= prices[i]:
result[stack.pop()] = prices[stack[-1]] - prices[i]
stack.append(i)
while stack:
result[stack.pop()] = prices[stack[-1]]
return result
# Example usage:
prices = [8, 4, 6, 2, 3]
print(finalPrices(prices)) # Output: [4, 2, 4, 2, 3]
n
is the length of the prices array.
This approach ensures that we efficiently find the next lower price for each item with a linear scan through the list, providing a significant improvement over a naive O(n^2) approach.
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?