Leetcode #2969: Minimum Number of Coins for Fruits II
In this guide, we solve Leetcode #2969 Minimum Number of Coins for Fruits II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Queue, Array, Dynamic Programming, Monotonic Queue, Heap (Priority Queue)
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: prices = [3,1,2]
Output: 4
Explanation: You can acquire the fruits as follows:
- Purchase the 1st fruit with 3 coins, and you are allowed to take the 2nd fruit for free.
- Purchase the 2nd fruit with 1 coin, and you are allowed to take the 3rd fruit for free.
- Take the 3rd fruit for free.
Note that even though you were allowed to take the 2nd fruit for free, you purchased it because it is more optimal.
It can be proven that 4 is the minimum number of coins needed to acquire all the fruits.
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.