Minimum Number of Coins for Fruits II — LeetCode 2969 Python Solution
- Problem
- #2969
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are at a fruit market with different types of exotic fruits on display. You are given a 1-indexed array prices, where prices[i] denotes the number of coins needed to purchase the ith fruit.
Example
- Input
- prices = [3,1,2]
- Output
- 4
- Explanation
- You can acquire the fruits as follows:
Python solution
class Solution:
def minimumCoins(self, prices: List[int]) -> int:
n = len(prices)
q = deque()
for i in range(n, 0, -1):
while q and q[0] > i * 2 + 1:
q.popleft()
if i <= (n - 1) // 2:
prices[i - 1] += prices[q[0] - 1]
while q and prices[q[-1] - 1] >= prices[i - 1]:
q.pop()
q.append(i)
return prices[0]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2969. Minimum Number of Coins for Fruits II is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2969. Minimum Number of Coins for Fruits II?
- LeetCode 2969. Minimum Number of Coins for Fruits II is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2969. Minimum Number of Coins for Fruits II?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2969. Minimum Number of Coins for Fruits II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2969. Minimum Number of Coins for Fruits II cover?
- LeetCode 2969. Minimum Number of Coins for Fruits II is tagged Queue, Array, Dynamic Programming, Monotonic Queue and Heap (Priority Queue) on LeetCode.
- Is LeetCode 2969. Minimum Number of Coins for Fruits II a premium problem?
- Yes. LeetCode 2969. Minimum Number of Coins for Fruits II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.