Minimum Cost to Merge Stones - Problem
Minimum Cost to Merge Stones
You're given
š Rules:
⢠Each move merges exactly
⢠The cost of merging equals the total stones in those
⢠You must merge ALL piles into ONE final pile
šÆ Goal: Return the minimum cost to merge all stones, or
Example: With
⢠Merge piles 1&2: cost = 3+2 = 5, result =
⢠Merge piles 1&2: cost = 5+4 = 9, result =
⢠Merge piles 1&2: cost = 9+1 = 10, result =
⢠Total cost = 5+9+10 = 24
You're given
n piles of stones arranged in a row, where the i-th pile contains stones[i] stones. Your task is to merge all piles into a single pile with minimum cost.š Rules:
⢠Each move merges exactly
k consecutive piles into one pile⢠The cost of merging equals the total stones in those
k piles⢠You must merge ALL piles into ONE final pile
šÆ Goal: Return the minimum cost to merge all stones, or
-1 if impossible.Example: With
stones = [3,2,4,1] and k = 2:⢠Merge piles 1&2: cost = 3+2 = 5, result =
[5,4,1]⢠Merge piles 1&2: cost = 5+4 = 9, result =
[9,1]⢠Merge piles 1&2: cost = 9+1 = 10, result =
[10]⢠Total cost = 5+9+10 = 24
Input & Output
example_1.py ā Basic Case
$
Input:
stones = [3,2,4,1], k = 2
āŗ
Output:
20
š” Note:
Step 1: Merge piles 1&2: [3,2,4,1] ā [5,4,1], cost = 5. Step 2: Merge piles 2&3: [5,4,1] ā [5,5], cost = 9. Step 3: Merge piles 1&2: [5,5] ā [10], cost = 10. Total cost = 5 + 9 + 10 = 24. But there's an optimal path: Step 1: [3,2,4,1] ā [3,6,1], cost = 6. Step 2: [3,6,1] ā [9,1], cost = 9. Step 3: [9,1] ā [10], cost = 10. Total = 20.
example_2.py ā Impossible Case
$
Input:
stones = [3,2,4,1], k = 3
āŗ
Output:
-1
š” Note:
With k=3, we need to merge 3 piles at a time. Starting with 4 piles, after one merge we have 2 piles. But we can't merge 2 piles with k=3. The feasibility condition (n-1) % (k-1) = (4-1) % (3-1) = 3 % 2 = 1 ā 0, so it's impossible.
example_3.py ā Single Pile
$
Input:
stones = [6], k = 3
āŗ
Output:
0
š” Note:
Already have just one pile, so no merging needed. Cost is 0.
Constraints
- 1 ⤠stones.length ⤠30
- 1 ⤠stones[i] ⤠100
- 2 ⤠k ⤠stones.length
- Key constraint: Solution exists only if (n-1) % (k-1) == 0
Visualization
Tap to expand
Understanding the Visualization
1
Check Feasibility
Verify that merging is mathematically possible using (n-1) % (k-1) == 0
2
Build Prefix Sums
Create prefix sum array for O(1) range sum queries during DP
3
Initialize Base Cases
Single piles (dp[i][i][1]) require 0 cost to 'merge' into 1 pile
4
Fill DP Table
For each interval [i,j], compute minimum cost to create p piles
5
Merge to One Pile
To get 1 pile from interval [i,j]: first create k piles, then merge them
Key Takeaway
šÆ Key Insight: This is an interval DP problem where we must first verify feasibility using (n-1) % (k-1) == 0, then use 3D dynamic programming to track the minimum cost of merging any subrange into any number of piles, ultimately building up to the answer.
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code