Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find Final Prices With a Special Discount in a Shop in Python
Given an array of prices, we need to find the final prices after applying a special discount. For each item at index i, we get a discount equal to the price of the first item at index j where j > i and prices[j] ? prices[i].
Problem Understanding
The discount rule works as follows ?
For item at index i, look for the first item at index j where j > i
If prices[j] ? prices[i], then discount = prices[j]
Final price = prices[i] − prices[j]
If no such j exists, no discount is applied
Example Walkthrough
For prices = [16, 8, 12, 4, 6] ?
Item 0 (price=16): First smaller/equal item is at index 1 (price=8), so final price = 16 − 8 = 8
Item 1 (price=8): First smaller/equal item is at index 3 (price=4), so final price = 8 − 4 = 4
Item 2 (price=12): First smaller/equal item is at index 3 (price=4), so final price = 12 − 4 = 8
Item 3 (price=4): No item after index 3 is ? 4, so no discount, final price = 4
Item 4 (price=6): No items after index 4, so no discount, final price = 6
Solution Implementation
def final_prices_with_discount(prices):
result = prices.copy() # Create a copy to avoid modifying original
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[j] <= prices[i]:
result[i] = prices[i] - prices[j]
break
return result
# Test the solution
prices = [16, 8, 12, 4, 6]
final_prices = final_prices_with_discount(prices)
print("Original prices:", prices)
print("Final prices: ", final_prices)
Original prices: [16, 8, 12, 4, 6] Final prices: [8, 4, 8, 4, 6]
Step-by-Step Algorithm
The algorithm follows these steps ?
Create a copy of the original prices array
-
For each item at index i from 0 to length-1:
Search for the first item at index j where j > i
If prices[j] ? prices[i], apply discount and break
If no such item found, keep original price
Return the result array
Alternative Test Case
def final_prices_with_discount(prices):
result = prices.copy()
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[j] <= prices[i]:
result[i] = prices[i] - prices[j]
break
return result
# Test with different prices
test_prices = [10, 1, 1, 6]
print("Test prices:", test_prices)
print("Final prices:", final_prices_with_discount(test_prices))
Test prices: [10, 1, 1, 6] Final prices: [9, 0, 1, 6]
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n²) | Nested loops in worst case |
| Space | O(n) | Additional array for result |
Conclusion
This solution uses a brute force approach to find the first eligible discount for each item. The nested loop structure ensures we find the nearest qualifying discount, making it suitable for the given problem constraints.
