Final Prices With a Special Discount in a Shop

You are given an integer array `prices` where `prices[i]` is the price of the `i`th item in a shop. Buying item `i` earns a discount equal to `prices[j]`, where `j` is the smallest index with `j > i` and `prices[j] <= prices[i]`. If no such `j` exists there is no discount. Return an array `answer` where `answer[i]` is the price you finally pay for item `i`.

30:00

Final Prices With a Special Discount in a Shop
easy
Free written solution
Topics
Companies

You are given an integer array prices where prices[i] is the price of the ith item in a shop. Buying item i earns a discount equal to prices[j], where j is the smallest index with j > i and prices[j] <= prices[i]. If no such j exists there is no discount. Return an array answer where answer[i] is the price you finally pay for item i.

Example 1:
Input: {"prices":[8,4,6,2,3]}
Output: [4,2,4,2,3]
Constraints:
  • 1≤prices.length≤5001 \leq \text{prices.length} \leq 500

  • 1≤prices[i]≤10001 \leq \text{prices}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"prices":[8,4,6,2,3]}

prices: red cap = discount taken

● waiting

8

0

8

4

1

4

6

2

6

2

3

2

3

4

3

Copy prices into result. A stack will hold the indices of items still waiting for a later item that is cheaper or equal.

stack: items waiting for a discount (prices rise to the top)

size 0

empty

discounts given 0
items scanned 0 / 5
Variables
VariableValue
stack[]
DepthFunction Call
Stack empty
0/14