Minimum Number of Coins for Fruits II - 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 i-th fruit.
The fruit market has the following offer: If you purchase the i-th fruit at prices[i] coins, you can get the next i fruits for free.
Note that even if you can take fruit j for free, you can still purchase it for prices[j] coins to receive a new offer.
Return the minimum number of coins needed to acquire all the fruits.
Input & Output
Example 1 — Basic Purchase Strategy
$
Input:
prices = [3,1,2]
›
Output:
4
💡 Note:
Buy fruit 1 for 3 coins (get fruit 2 free), then buy fruit 3 for 2 coins. Total: 3 + 1 = 4 coins. Alternative: buy fruit 2 for 1 coin (get fruits 3-4 free, but fruit 4 doesn't exist), then buy fruit 1 for 3 coins. Total: 1 + 3 = 4 coins.
Example 2 — Optimal Free Fruits
$
Input:
prices = [1,10,1,1]
›
Output:
2
💡 Note:
Buy fruit 1 for 1 coin (get fruit 2 free), then buy fruit 4 for 1 coin. Fruits 1 and 4 cost 1+1=2 coins, and fruit 2 is free from buying fruit 1, fruit 3 needs separate purchase but we can take it free by buying fruit 4 after taking fruit 2.
Example 3 — Single Fruit
$
Input:
prices = [26]
›
Output:
26
💡 Note:
Only one fruit available, must buy it for 26 coins. No free fruits possible.
Constraints
- 1 ≤ prices.length ≤ 1000
- 1 ≤ prices[i] ≤ 105
- Array is 1-indexed for the problem logic
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of fruit prices [3,1,2]
2
Purchase Strategy
Buy fruit 1 → get fruit 2 free, buy fruit 3
3
Output
Minimum cost: 4 coins
Key Takeaway
🎯 Key Insight: Each purchase creates a range of free fruits - optimize by considering all possible purchase combinations with dynamic programming
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code