KatInterview

Final Sale Prices with Discount Tracking

Stacks & QueuesAuto-graded · 27 test cases
HardAuto-gradedStacks & Queuesmonotonic-stackarraysaggregation

Last 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:

  1. An integer: the sum of all final selling prices
  2. 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,000
  • 1 ≤ prices[i] ≤ 1,000,000 for 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.