Final Sale Prices with Discount Tracking
Stacks & QueuesAuto-graded · 27 test casesLast updated
Tests monotonic stack usage to efficiently find next smaller-or-equal elements and aggregate results with index tracking.
You're processing a sequence of items for sale. Given an array prices where each element represents an item's original price, determine the final selling price for each item using this rule:
For each item at position i, scan forward through the remaining items. If you find an item at position j (where j > i) whose price is less than or equal to prices[i], apply a discount: the final price becomes prices[i] - prices[j], using the first such item encountered. If no such item exists to the right, the item sells at its original price with no discount.
Return a list containing exactly two elements:
- An integer: the sum of all final selling prices
- A list of integers: the indices (0-indexed) of all items sold at their original price, in ascending order
If no items are sold at original price, the second element should be an empty list.
Constraints
0 ≤ len(prices) ≤ 100,0001 ≤ prices[i] ≤ 1,000,000for all valid indices- All prices are positive integers
- Indices are 0-based
- When multiple items have the same price, the discount rule still applies (an item can be discounted by another item of equal price)
Examples
Example 1
Input: calculate_final_prices([5, 1, 3])
Output: [8, [1, 2]]
Example 2
Input: calculate_final_prices([8, 4, 6, 2, 3])
Output: [15, [3, 4]]
Example 3
Input: calculate_final_prices([1, 2, 3, 4, 5])
Output: [15, [0, 1, 2, 3, 4]]
Hints
Hint 1
Think about the 'next smaller-or-equal element' pattern—this is a classic use case for a monotonic stack.
Hint 2
Processing the array from right to left lets you build up candidate discount sources as you go.
Hint 3
Each index gets pushed to the stack once and popped at most once, making the algorithm linear despite the nested loop.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to find, for each item, the nearest item to its right with a price that doesn't exceed it. This is the "next smaller-or-equal element" pattern, which can be solved efficiently with a monotonic stack.
The strategy is to traverse the array from right to left, maintaining a stack of candidate indices. At each position i:
- Remove from the stack any indices whose prices are strictly greater than
prices[i]. These can never serve as discount sources for itemior any item to its left. - If the stack has elements remaining, the top element is the closest qualifying item to the right. Apply the discount using that price.
- If the stack is empty, no qualifying item exists, so this item sells at full price and we record its index.
- Push the current index onto the stack as a potential discount source for items to the left.
Since we collect full-price indices while moving right-to-left, we reverse the list before returning to get ascending order.
Why This Works
The key insight is that once we're at position i, any index p with prices[p] > prices[i] can be safely discarded. For any item at position k < i, if prices[p] would qualify as a discount source (meaning prices[p] ≤ prices[k]), then prices[i] must also qualify since prices[i] < prices[p] ≤ prices[k]. Because i is closer to k than p is, item i would be chosen first, making p irrelevant.
After removing all strictly greater elements, the remaining stack contains only valid candidates in increasing order of distance from i. The top element is therefore the nearest qualifying index.
Note that we pop when prices[stack[-1]] > prices[i], not when equal. Equal prices are valid discount sources according to the problem rules.
Complexity
Time: O(n). Each index is pushed onto the stack exactly once and popped at most once. Though there's a while loop inside the for loop, the total number of pops across the entire algorithm cannot exceed n.
Space: O(n) for the stack, the final prices array, and the indices list.
from typing import List
def calculate_final_prices(prices: List[int]) -> List[int]:
n = len(prices)
total = 0
full_price_indices = []
stack = []
final_prices = [0] * n
for i in range(n - 1, -1, -1):
while stack and prices[stack[-1]] > prices[i]:
stack.pop()
if stack:
final_prices[i] = prices[i] - prices[stack[-1]]
else:
final_prices[i] = prices[i]
full_price_indices.append(i)
stack.append(i)
total += final_prices[i]
full_price_indices.reverse()
return [total, full_price_indices]