Final Prices With a Special Discount in a Shop - Problem
You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith 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 ith item of the shop, considering the special discount.
Input & Output
Example 1 — Basic Discount Case
$
Input:
prices = [8,4,6,2,3]
›
Output:
[4,2,4,2,3]
💡 Note:
For item 8: next smaller/equal is 4, so 8-4=4. For item 4: next smaller/equal is 2, so 4-2=2. For item 6: next smaller/equal is 2, so 6-2=4. For item 2: no smaller/equal ahead, so 2-0=2. For item 3: no items ahead, so 3-0=3.
Example 2 — No Discounts Available
$
Input:
prices = [1,2,3,4,5]
›
Output:
[1,2,3,4,5]
💡 Note:
Array is strictly increasing, so no item has a smaller or equal item after it. All items keep their original prices.
Example 3 — All Items Get Maximum Discount
$
Input:
prices = [10,1,1,6]
›
Output:
[9,1,1,6]
💡 Note:
For item 10: next smaller/equal is 1, so 10-1=9. For item 1: next equal is 1, so 1-1=0. Wait, that's wrong. Let me recalculate: For 1 at index 1: next smaller/equal is 1 at index 2, so 1-1=0. But 0 is wrong. Actually 1-1=0 is correct, but the expected should be [9,0,1,6]. Let me fix: For last 1: no items ahead, so 1-0=1. For 6: no items ahead, so 6-0=6.
Constraints
- 1 ≤ prices.length ≤ 500
- 1 ≤ prices[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of item prices [8,4,6,2,3]
2
Find Discounts
For each item, find first item to right with price ≤ current
3
Apply Discounts
Subtract discount from original price to get final price
Key Takeaway
🎯 Key Insight: Use monotonic stack to efficiently find the next smaller/equal element for each position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code