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
Minimum Coins for Fruits II INPUT prices array (1-indexed) 3 i=1 1 i=2 2 i=3 1 2 3 Market Offer Rule: Buy fruit i at prices[i] Get next i fruits FREE Input: prices = [3,1,2] n = 3 fruits total Goal: Acquire all fruits ALGORITHM STEPS 1 Buy Fruit 1 Pay 3 coins Free: next 1 fruit (i=2) 2 Get Fruit 2 Free Cost: 0 coins But wait - better option! 3 Buy Fruit 2 Instead Pay 1 coin Free: next 2 fruits (i=3,4) 4 Get Fruit 3 Free Cost: 0 coins All fruits acquired! DP Approach: dp[i] = min cost for fruits i..n dp[i] = prices[i] + min(dp[i+1]..dp[2i+1]) FINAL RESULT Cost Breakdown: Fruit 1: 3 coins (buy) Fruit 2: 1 coin (buy) Fruit 3: 0 coins (free) Total: 3 + 1 = 4 coins OUTPUT 4 [OK] Solution Verified All 3 fruits acquired Minimum coins = 4 Key Insight: Even when a fruit is free, buying it may unlock more free fruits. Use monotonic deque optimization: maintain minimum dp values in sliding window for O(n) time complexity. Transition: dp[i] = prices[i] + min(dp[j]) where i+1 <= j <= min(2i+1, n+1) TutorialsPoint - Minimum Number of Coins for Fruits II | Optimal Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen