Final Prices With a Special Discount in a Shop Problem
Description
LeetCode Problem 1475.
You are given an integer array 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 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 i^th item of the shop, considering the special discount.
Example 1:
Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
Explanation:
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.
Example 2:
Input: prices = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: In this case, for all items, you will not receive any discount at all.
Example 3:
Input: prices = [10,1,1,6]
Output: [9,0,1,6]
Constraints:
1 <= prices.length <= 5001 <= prices[i] <= 1000
Solution
Approach: Monotonic Stack
For each item we need the first price to its right that is less than or equal to it. Checking every later item works for 500 prices, but a stack does it in one pass.
Keep a stack of indices of items that have not found their discount yet. Scan the prices from left to right; for the price p at index j:
- While the item on top of the stack has a price
>= p,pis the first such price to its right, so subtractpfrom its answer and pop it. - Then push
j: it is now waiting for its own discount.
Items stay on the stack only while no later price has been small enough, so the prices on the stack are strictly increasing from bottom to top. That is why we can stop popping as soon as the top is cheaper than p: everything below it is cheaper still. Items left on the stack at the end get no discount and keep their full price.
The comparison is >=, not >: an equal price counts as a discount, as in [10,1,1,6], where the first 1 is reduced to 0.
Complexity: O(n) time, since each index is pushed and popped at most once, and O(n) extra space for the stack.
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
answer = prices[:]
waiting = [] # indices still without a discount; their prices increase strictly
for j, p in enumerate(prices):
# p is the first price at or below each of these, so it is their discount
while waiting and prices[waiting[-1]] >= p:
answer[waiting.pop()] -= p
waiting.append(j)
return answer