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: [3,2,4,1] with k=23241Initial: 4 piles541Step 1: Merge [3,2] → cost = 510Final: Total cost = 5 + 5 + 10 = 20
Understanding the Visualization
1
Input
stones = [3,2,4,1], k = 2
2
Merge Process
Find optimal sequence to merge k consecutive piles
3
Output
Minimum total cost = 20
Key Takeaway
🎯 Key Insight: Only possible when (n-1) % (k-1) == 0, use interval DP to find optimal merge sequence
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