Minimum Cost to Merge Stones

Hard

Description

There are n piles of stones. Each move, merge k consecutive piles into one, costing sum of stones. Return minimum cost to merge all into one pile.

Examples

Input:stones = [3,2,4,1], k = 2
Output:20
Explanation:

Merge [3,2] cost 5, [4,1] cost 5, [5,5] cost 10. Total 20.

Input:stones = [1], k = 2
Output:1
Explanation:

Edge case with a single-element array.

Input:stones = [6, 4, 4, 6], k = 4
Output:40
Explanation:

Since k=4 and there are exactly 4 piles, all piles merge in one move. The cost is the sum of all stones: 6+4+4+6=20.

Constraints

  • n == stones.length
  • 1 ≤ n ≤ 30
  • 2 ≤ k ≤ 30

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!