Final Prices With a Special Discount

Easy StackMonotonic StackArray

Problem

You are given an array prices where prices[i] is the price of the i-th item in a shop. There is a special discount: for item i you receive a discount equal to prices[j] — the price of the first later item j > i whose price is less than or equal to prices[i]. If no such j exists, you pay full price. Return an array where the i-th value is the final price paid for item i.

Example 1 Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Explain: Item 0 (8) is discounted by item 1 (4). Item 1 (4) by item 3 (2). Item 2 (6) by item 3 (2). Item 3 (2) has no later price below it, item 4 keeps its price.
Example 2 Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Explain: Every later price is larger, so no discount ever applies.

Constraints

Approach — Monotonic Stack

This is a Monotonic Stack problem. The idea: scan once and keep a stack whose order stays meaningful, popping elements as soon as a later value resolves them. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def finalPrices(self, prices):
        res = prices[:]
        st = []
        for i, p in enumerate(prices):
            while st and prices[st[-1]] >= p:
                res[st.pop()] -= p
            st.append(i)
        return res

Java

import java.util.ArrayDeque;
import java.util.Deque;

class Solution {
    public int[] finalPrices(int[] prices) {
        int n = prices.length;
        int[] res = prices.clone();
        // Monotonic stack of indices whose prices stay non-increasing.
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            // prices[i] is the first later price <= the items on top.
            while (!stack.isEmpty() && prices[stack.peek()] >= prices[i]) {
                int j = stack.pop();
                res[j] = prices[j] - prices[i];
            }
            stack.push(i);
        }
        return res;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Final Prices With a Special Discount interactively → ← All solutions