# Program to find Final Prices With a Special Discount in a Shop in Python

Suppose we have an array called prices where prices[i] represents price of the ith item in a shop. There is a special offer going on, if we buy the ith item, then we will get a discount equivalent to prices[j] where j is the minimum index such that j > i and price of jth item is less or same as price of ith item (i.e. prices[j] <= prices[i]), otherwise, we will not receive any discount at all. We have to find an array where the ith element is the final price that we will pay for the ith item of the shop considering the special discount.

So, if the input is like prices = [16,8,12,4,6], then the output will be [8, 4, 8, 4, 6], as price of item0 is 16, so we will get a discount equivalent to prices[1]=8, then, the final price will be 8 - 4 = 4. For item1 the price[1] is 8 we will receive a discount equivalent to prices[3]=2, so, the final price we will pay is 8 - 4 = 4. For item 2 with price[2] is 12 and we will get a discount value same as prices[3] = 4, therefore, the final price we will pay is 12 - 4 = 8. And for items 3 and 4 we will not receive any discount.

To solve this, we will follow these steps −

• for i in range 0 to size of prices, do

• for j in range i+1 to size of prices, do

• if prices[i] >= prices[j], then

• prices[i] := prices[i] - prices[j]

• come out from the loop

• otherwise,

• j := j + 1

• return prices

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(prices):
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if(prices[i]>=prices[j]):
prices[i]-=prices[j]
break
else:
j+=1
return prices

prices = [16,8,12,4,6]
print(solve(prices))

## Input

[16,8,12,4,6]

## Output

[8, 4, 8, 4, 6]

Updated on: 17-May-2021

814 Views