You're shopping at a special store where each item has a smart discount system! The store offers an innovative discount policy: when you buy any item, you'll receive a discount equal to the price of the next cheaper or equally-priced item that appears later in the store.
Given an integer array prices where prices[i] represents the price of the i-th item, your task is to calculate the final discounted price for each item.
Discount Rules:
- For item at position
i, find the first item at positionjwherej > iandprices[j] ≤ prices[i] - The discount amount equals
prices[j] - If no such item exists, no discount is applied
Return an array where each element represents the final price after applying the discount (original price minus discount).
Example: If prices = [8, 4, 6, 2, 3], then:
• Item $8 gets $4 discount (next cheaper item) → Final: $4
• Item $4 gets $2 discount → Final: $2
• Item $6 gets $2 discount → Final: $4
• Item $2 gets no discount → Final: $2
• Item $3 gets no discount → Final: $3
Input & Output
Visualization
Time & Space Complexity
For each of the n items, we potentially scan through all remaining n-1 items in the worst case
Only using constant extra space besides the input and output arrays
Constraints
- 1 ≤ prices.length ≤ 500
- 1 ≤ prices[i] ≤ 103
- All prices are positive integers