KatInterview

Checkout Totals After Next Cheaper Coupon Item

Stacks & QueuesAuto-graded · 25 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stackarraysnext-smaller-element

Last updated

Find, for each element, the nearest later value that is less than or equal to it and subtract it, which tests monotonic stack reasoning on arrays.

A shop lines up n products in a row, and prices[i] is the listed price of the product at position i.

A rebate rule applies to each product. Look at the products that come after it in the row, from nearest to farthest. The first one whose listed price is less than or equal to the current product's listed price provides the rebate: its listed price is subtracted from the current product's price.

If no later product has a listed price less than or equal to the current one, the product gets no rebate and keeps its listed price.

Rebates are always computed from the original listed prices, never from already-reduced prices.

Return a list of the same length where entry i is the amount paid for the product at position i.

Input

  • prices: a list of integers, the listed prices in row order.

Output

  • A list of integers of length n, the amounts paid for each product.

Rules and edge cases

  • A price equal to the current one counts as a valid rebate source (for example, [5, 5] gives [0, 5]).
  • The last product never receives a rebate.
  • A list with a single product returns that same price.

Constraints

  • 1 <= n <= 2 * 10^5
  • 1 <= prices[i] <= 10^9
  • A solution that compares every pair of positions will be too slow for the largest inputs.

Examples

Example 1

Input: apply_next_rebate([8, 4, 6, 2, 3])

Output: [4, 2, 4, 2, 3]

Example 2

Input: apply_next_rebate([1, 2, 3, 4, 5])

Output: [1, 2, 3, 4, 5]

Example 3

Input: apply_next_rebate([10, 1, 1, 6])

Output: [9, 0, 1, 6]

Hints

Hint 1

For each position you need the nearest element to its right that is less than or equal to it. Think of this as a 'next smaller or equal element' problem.

Hint 2

Scan from right to left while keeping a stack of candidate values from the part of the row you have already seen. A candidate that is strictly larger than the current price can never serve as its rebate.

Hint 3

Pop stack values strictly greater than the current price, then the top (if any) is the rebate. Push the current price afterwards. Use a strict comparison when popping so equal values stay and qualify.