Minimum Cost to Merge Stones
Master this topic with zero to advance depth.
Minimum Cost to Merge Stones
There are n piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.
Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Visual Representation
stones = [3, 2, 4, 1], k = 2
[3, 2, 4, 1] -> [5, 4, 1] (cost 5)
[5, 4, 1] -> [5, 5] (cost 5)
[5, 5] -> [10] (cost 10)
Total Cost: 20 (Min)Examples
After merging 3 piles, we have 2 piles left. We need exactly k=3 piles to merge.
Level I: Brute Force (Recursion)
Intuition
Try all possible splitting points in the current range [i, j] to merge into m piles. This is a classic exhaustive search for partition problems.
Thought Process
solve(i, j, piles)returns min cost to mergestones[i...j]intopilespiles.- Transitions:
- To get
pilespiles from[i, j], we can split into[i, k](merged into1pile) and[k+1, j](merged intopiles-1piles). solve(i, j, piles) = min(solve(i, k, 1) + solve(k + 1, j, piles - 1)).
- To get
- Base case:
solve(i, i, 1) = 0.
Detailed Dry Run
stones = [3, 2, 4], K = 3
- solve(0, 2, 1) = solve(0, 2, 3) + sum(3, 2, 4).
- solve(0, 2, 3) = split into [0,0] (1 pile) and [1,2] (2 piles).
- Result: 9.
Level II: Memoization (Top-Down 3D)
Intuition
Cache the result of solve(i, j, m) — the minimum cost to merge stones[i..j] into m piles. This avoids recomputing the same interval+pile-count combinations.
Visual
solve(0,3,1) [merge ALL into 1 pile]
-> solve(0,1,1) + solve(2,3,1) [split and merge]
Both sub-calls cached after first computation!Detailed Dry Run
stones=[3,2,4], K=3. solve(0,2,1): need K=3 piles first. solve(0,2,3)=0 (3 stones, 3 piles is base). Cost=9. Cached.
Level III: Dynamic Programming (Interval/3D)
Intuition
This is a complex interval DP problem. We want to find the min cost to merge stones in range [i, j] into p piles.
Thought Process
dp[i][j][m]means the min cost to merge stones instones[i...j]intompiles.- Transitions:
- To merge
[i, j]intompiles, we can split it into[i, k](merged into1pile) and[k+1, j](merged intom-1piles). dp[i][j][m] = min(dp[i][k][1] + dp[k+1][j][m-1])forkin[i, j-1].- Base Case:
dp[i][i][1] = 0(single pile is already 1 pile).
- To merge
- When
m == 1, the cost isdp[i][j][k] + sum(stones[i...j]).
Detailed Dry Run
This is a classical matrix chain multiplication style problem. The state dp[i][j][m] helps track number of piles remaining, which is crucial because we can only merge EXACTLY K piles at once.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.