AlgoInsight

DSA problem

Final Prices With a Special Discount in a Shop

EasyMonotonic StackPattern: Monotonic Stacktop600AmazonGoogleMicrosoftApple

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: if you buy the i-th item, you receive a discount equivalent to prices[j] where j is the smallest index such that j > i and prices[j] <= prices[i]. If no such j exists, you receive no discount. Return an array where the i-th element is the final price you pay for the i-th item — that is, prices[i] - discount.

The brute-force approach is straightforward: for each item i, walk to the right scanning prices[j] until you find the first j with prices[j] <= prices[i]. That costs O(n²) time in the worst case (already-sorted-descending input), which is wasteful because many of those scans repeat work.

A monotonic stack solves this in a single linear pass. We iterate left-to-right and maintain a stack of indices whose prices are still waiting for a discount-eligible smaller-or-equal price. The stack stays monotonically non-increasing from bottom to top: when we see a new price prices[i], any index on top of the stack whose price is greater than or equal to prices[i] has just found its discount, so we pop and subtract prices[i] from answer[top].

After processing the array, anything still on the stack never found a smaller-or-equal price to its right and keeps its original price. Total work is O(n) because each index is pushed and popped at most once.

Examples

Example 1
Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
Explanation: Item 0 (price 8): the next price <= 8 is 4, so final price = 8 - 4 = 4. Item 1 (price 4): next <= 4 is 2, so 4 - 2 = 2. Item 2 (price 6): next <= 6 is 2, so 6 - 2 = 4. Item 3 (price 2): next <= 2 is 3? No 3 > 2; nothing qualifies, so 2. Item 4: nothing to the right, so 3.
Example 2
Input: prices = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: The prices are strictly increasing, so no item ever finds a smaller-or-equal price to its right — every item keeps its original price.
Example 3
Input: prices = [10,1,1,6]
Output: [9,0,1,6]
Explanation: Item 0 (10) finds 1 next, paying 9. Item 1 (1) finds another 1, paying 0. Item 2 (1) has no later price <= 1 (6 > 1), so it pays 1. Item 3 stays at 6.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

monotonic-stackstackarray

Browse all DSA problems