Minimum Cost to Merge Stones - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: stones = [3,2,4,1], k = 2
Output: 20
💡 Note: Merge [3,2] for cost 5 → [5,4,1]. Merge [4,1] for cost 5 → [5,5]. Merge [5,5] for cost 10. Total: 5+5+10=20
Example 2 — Impossible Case
$ Input: stones = [3,2,4,1], k = 3
Output: -1
💡 Note: Cannot merge 4 piles into 1 with k=3. Need (n-1) % (k-1) = 0, but (4-1) % (3-1) = 1 ≠ 0
Example 3 — Single Pile
$ Input: stones = [3,5,1,2,6], k = 3
Output: 25
💡 Note: Merge [3,5,1] for cost 9 → [9,2,6]. Merge [9,2,6] for cost 17. Total: 9+17=26. Wait, optimal is different - need to find minimum path

Constraints

  • n == stones.length
  • 1 ≤ n ≤ 30
  • 1 ≤ stones[i] ≤ 100
  • 2 ≤ k ≤ n

Visualization

Tap to expand
Minimum Cost to Merge Stones INPUT Stone Piles Array: 3 2 4 1 i=0 i=1 i=2 i=3 stones = [3, 2, 4, 1] k = 2 Merge k=2 consecutive piles at a time (n-1) % (k-1) = 0 [OK] ALGORITHM STEPS 1 Merge [3,2] = 5 Cost: 5, Array: [5,4,1] 2 Merge [4,1] = 5 Cost: 5+5=10, Array: [5,5] 3 Merge [5,5] = 10 Cost: 10+10=20, Array: [10] 4 DP State dp[i][j] = min cost [i..j] DP Recurrence: dp[i][j] = min( dp[i][m] + dp[m+1][j] ) + sum[i..j] if (j-i) % (k-1) == 0 Optimal Merge Sequence: [3,2,4,1] --> [5,4,1] --> [5,5] --> [10] FINAL RESULT All stones merged into one pile: 10 stones Output: 20 Cost Breakdown: 5 + 5 + 10 = 20 Key Insight: Use interval DP where dp[i][j] represents minimum cost to merge stones from index i to j. Merging is possible only when (n-1) % (k-1) == 0. Split intervals optimally and add merge cost when the interval length allows reducing to exactly one pile. Time: O(n^3/k), Space: O(n^2). TutorialsPoint - Minimum Cost to Merge Stones | Dynamic Programming (Interval DP)
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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