Problem Description
Given an array of integers representing prices of items in a shop, for each item, find the next item in the list (with a greater index) that has a price less than or equal to the current price and subtract that price as a discount. If no such item exists, the original price is paid. Return an array containing the final prices for all items after applying the discount.
Key Insights
- A brute-force approach would check each subsequent item for every index which can be inefficient.
- Using a monotonic stack helps in efficiently finding the next smaller or equal price for each item.
- Traverse the array once, while maintaining a stack of indices where the discount has not yet been applied.
- When a price qualifies as the discount for the items stored in the stack, update those items.
Space and Time Complexity
Time Complexity: O(n) - Each element is pushed and popped from the stack at most once. Space Complexity: O(n) - In the worst-case scenario, all elements are stored in the stack.
Solution
The solution uses a monotonic stack to track the indices of prices that have not yet found their discount. As we iterate over the prices:
- Check if the current price can act as a discount for any previously seen elements (stored in the stack) by comparing it with the price at the index on the top of the stack.
- If the current price is less than or equal to the price at the top of the stack, it qualifies as a discount; subtract it from that price and pop that index from the stack.
- Push the current index onto the stack. Once the iteration is complete, any index left in the stack did not encounter a valid discount and remains at its original price.