Final Prices With a Special Discount in a Shop — LeetCode 1475 Python Solution
EasyStackArrayMonotonic Stack
- Problem
- #1475
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop.
Example
- Input
- prices = [8,4,6,2,3]
- Output
- [4,2,4,2,3]
- Explanation
- For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
Python solution
Python
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
stk = []
for i in reversed(range(len(prices))):
x = prices[i]
while stk and x < stk[-1]:
stk.pop()
if stk:
prices[i] -= stk[-1]
stk.append(x)
return pricesComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1475. Final Prices With a Special Discount in a Shop is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1475. Final Prices With a Special Discount in a Shop?
- LeetCode 1475. Final Prices With a Special Discount in a Shop is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1475. Final Prices With a Special Discount in a Shop?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1475. Final Prices With a Special Discount in a Shop?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1475. Final Prices With a Special Discount in a Shop cover?
- LeetCode 1475. Final Prices With a Special Discount in a Shop is tagged Stack, Array and Monotonic Stack on LeetCode.