Checkout Totals After Next Cheaper Coupon Item
Stacks & QueuesAuto-graded · 25 test casesLast updated
Find, for each element, the nearest later value that is less than or equal to it and subtract it, which tests monotonic stack reasoning on arrays.
A shop lines up n products in a row, and prices[i] is the listed price of the product at position i.
A rebate rule applies to each product. Look at the products that come after it in the row, from nearest to farthest. The first one whose listed price is less than or equal to the current product's listed price provides the rebate: its listed price is subtracted from the current product's price.
If no later product has a listed price less than or equal to the current one, the product gets no rebate and keeps its listed price.
Rebates are always computed from the original listed prices, never from already-reduced prices.
Return a list of the same length where entry i is the amount paid for the product at position i.
Input
prices: a list of integers, the listed prices in row order.
Output
- A list of integers of length
n, the amounts paid for each product.
Rules and edge cases
- A price equal to the current one counts as a valid rebate source (for example,
[5, 5]gives[0, 5]). - The last product never receives a rebate.
- A list with a single product returns that same price.
Constraints
1 <= n <= 2 * 10^51 <= prices[i] <= 10^9- A solution that compares every pair of positions will be too slow for the largest inputs.
Examples
Example 1
Input: apply_next_rebate([8, 4, 6, 2, 3])
Output: [4, 2, 4, 2, 3]
Example 2
Input: apply_next_rebate([1, 2, 3, 4, 5])
Output: [1, 2, 3, 4, 5]
Example 3
Input: apply_next_rebate([10, 1, 1, 6])
Output: [9, 0, 1, 6]
Hints
Hint 1
For each position you need the nearest element to its right that is less than or equal to it. Think of this as a 'next smaller or equal element' problem.
Hint 2
Scan from right to left while keeping a stack of candidate values from the part of the row you have already seen. A candidate that is strictly larger than the current price can never serve as its rebate.
Hint 3
Pop stack values strictly greater than the current price, then the top (if any) is the rebate. Push the current price afterwards. Use a strict comparison when popping so equal values stay and qualify.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each product needs the nearest later price that is less than or equal to its own. Checking every later position for every product costs O(n²), which is too slow for n = 2 * 10^5. A monotonic stack solves it in linear time.
Scan the row from right to left, keeping a stack of candidate rebate values taken from the positions already processed (everything to the right of the current index). The top of the stack is always the candidate closest to the current position.
At index i:
- Pop every value on the stack that is strictly greater than
prices[i]. These cannot be the rebate fori. - If the stack is not empty, its top is the nearest later price that is
<= prices[i]. Subtract it fromprices[i]. - Push
prices[i]so it can serve as a rebate for products further left.
If the stack is empty after popping, the result for i stays equal to prices[i].
Why it is correct
- After the pops, the remaining top is the closest value to the right that satisfies the
<=condition, because only values that fail the condition were removed and the stack keeps values ordered by closeness. - A popped value
x > prices[i]is never needed later. For any productk < ithat would acceptx(sox <= prices[k]), we haveprices[i] < x <= prices[k], soprices[i]also qualifies forkand is closer. Discardingxtherefore never changes an answer. - Popping only on strict
>keeps equal values, so equal prices correctly count as rebates.
Complexity
- Time: O(n). Each value is pushed once and popped at most once.
- Space: O(n) for the stack and the output list.
Reference solution
from typing import List
def apply_next_rebate(prices: List[int]) -> List[int]:
n = len(prices)
result = prices.copy()
stack = []
for i in range(n - 1, -1, -1):
while stack and stack[-1] > prices[i]:
stack.pop()
if stack:
result[i] = prices[i] - stack[-1]
stack.append(prices[i])
return result