Minimum Number of Coins for Fruits — LeetCode 2944 Python Solution
- Problem
- #2944
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an 0-indexed integer array prices where prices[i] denotes the number of coins needed to purchase the (i + 1)th fruit. The fruit market has the following reward for each fruit: If you purchase the (i + 1)th fruit at prices[i] coins, you can get any number of the next i fruits for free.
Python solution
class Solution:
def minimumCoins(self, prices: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i * 2 >= len(prices):
return prices[i - 1]
return prices[i - 1] + min(dfs(j) for j in range(i + 1, i * 2 + 2))
return dfs(1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2944. Minimum Number of Coins for Fruits 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 2944. Minimum Number of Coins for Fruits?
- LeetCode 2944. Minimum Number of Coins for Fruits is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2944. Minimum Number of Coins for Fruits?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2944. Minimum Number of Coins for Fruits?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2944. Minimum Number of Coins for Fruits cover?
- LeetCode 2944. Minimum Number of Coins for Fruits is tagged Queue, Array, Dynamic Programming, Monotonic Queue and Heap (Priority Queue) on LeetCode.