Skip to content
BytePatterns

Prices After the Next Discount

EasyStacks & Queues#monotonic-stack#next-smaller~15m

Problem

A shop lists item prices in shelf order. Buying item i earns a discount equal to the price of the first item to its right whose price is less than or equal to prices[i]. If no such item exists, there is no discount. Return the price actually paid for every item.

Examples

Input:  prices = [8, 4, 6, 2, 3]
Output: [4, 2, 4, 2, 3]
Why:    8 is discounted by 4, 4 and 6 are both discounted by 2, and 2 and 3 have no cheaper item after them
Input:  prices = [10, 1, 1, 6]
Output: [9, 0, 1, 6]
Why:    an equal price counts, so the first 1 is discounted by the second 1
Input:  prices = [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4, 5]
Why:    edge case, rising prices never meet a cheaper item to the right

Hints

0 / 3

Stuck on the idea rather than the code? Largest Rectangle covers it.