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 at index 1: next equal is 1 at index 2, so 1-1=0. For item 1 at index 2: no items ahead, so 1-0=1. For item 6: no items ahead, so 6-0=6.

Constraints

  • 1 ≤ prices.length ≤ 500
  • 1 ≤ prices[i] ≤ 1000

Visualization

Tap to expand
Final Prices With Special Discount INPUT prices array i=0 i=1 i=2 i=3 i=4 8 4 6 2 3 Finding discounts: 8-4=4 4-2=2 6-2=4 prices = [8,4,6,2,3] ALGORITHM STEPS 1 Use Monotonic Stack Stack stores indices of items awaiting discount 2 Iterate Left to Right For each price, check if it can be a discount 3 Pop and Apply Discount While stack top price >= current: apply discount 4 Push Current Index Add current index to stack for future discount Stack [indices] decreasing Time: O(n) | Space: O(n) FINAL RESULT answer array i=0 i=1 i=2 i=3 i=4 4 2 4 2 3 Calculations: i=0: 8-4 = 4 (j=1) i=1: 4-2 = 2 (j=3) i=2: 6-2 = 4 (j=3) i=3: 2-0 = 2 (no j) i=4: 3-0 = 3 (no j) Output: [4, 2, 4, 2, 3] OK - All discounts applied! Key Insight: A monotonic decreasing stack efficiently finds the next smaller or equal element for each item. When we encounter a price that can be a discount (smaller or equal), we pop from stack and apply it. Each element is pushed and popped at most once, giving O(n) time complexity. TutorialsPoint - Final Prices With a Special Discount in a Shop | Optimal Solution (Monotonic Stack)
Asked in
Amazon 15 Microsoft 12
53.7K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen