Ctrl K

Discount From a Cheaper Neighbor

Easy
Items stand in a row on a shelf, and prices[i] is the price of the item at position i. The shop runs a promotion: when you buy item i, you get a discount equal to the price of the nearest item to its right that costs no more than it does (prices[j] ≤ prices[i] with the smallest j > i). If there is no such item, there is no discount. Return an array whose value at position i is what you actually pay for item i.
Example 1
prices=[6, 9, 3, 5, 5] → [3, 6, 3, 0, 5]

6: the nearest price to the right that is not above 6 is 3, so you pay 3. 9: also 3, you pay 6. 3: nothing to its right is 3 or less, no discount. The first 5: the next 5 counts (an equal price qualifies), you pay 0. The last 5 gets no discount.

Example 2
prices=[2, 4, 8] → [2, 4, 8]

Prices only go up to the right, so no item gets a discount.

Example 3
prices=[1000] → [1000]
Constraints
  • 1 ≤ prices.length ≤ 500
  • 1 ≤ prices[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNext Larger on the Right EasyWater Between Walls HardBiggest Rectangle Under the Skyline HardBiggest Solid Panel Block HardPreorder of a Search Tree Medium
loading Python…
Input
prices=[6, 9, 3, 5, 5]
Expected
[3, 6, 3, 0, 5]

Run checks the first 3 tests in your browser. Submit checks all 113 tests on the server, hidden ones included.