Skip to problem
←

Minimum Cost to Merge Stones

Hard 0 attempts

You have a row of stone piles and a number k. In one move, you may merge exactly k piles that sit next to each other into a single pile, and that move costs the sum of the stones involved. Return the minimum total cost to merge all piles into exactly one pile, or -1 if this is impossible.

Piles cannot be reordered, and a newly merged pile may participate in later moves. Count its stones again when calculating those later costs. If there is already one pile, no moves are needed and the cost is 0, even when k exceeds the number of piles.

For [3,2,4,1] with k = 2, merge 3+2 for cost 5, then 4+1 for cost 5, then the two resulting piles for cost 10. The minimum total is 5 + 5 + 10 = 20.

Function contract

Implement mergeStones(stones, k). stones gives positive pile sizes in their fixed row order. Each move merges exactly k currently adjacent piles.

Output: Return the minimum sum of all merge costs, 0 if there is already one pile, or -1 if one pile cannot be reached.

Example 1

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

Example 2

Input
stones = [3,2,4,1]
k = 3
Output
-1
Constraints
  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 100
  • 2 <= k <= 30

Interval DP

Every merge reduces the pile count by k - 1, so one pile is reachable only when (n - 1) is divisible by k - 1.

Let dp[i][j] be the minimum cost to reduce that interval to the smallest feasible number of piles: 1 + ((j - i) % (k - 1)). Intervals shorter than k need no merge. Try split points in steps of k - 1 so the left interval can become one pile. If the full interval can become one pile, add its total stone count for the final merge; prefix sums provide that total in O(1).

javascript
function mergeStones(stones, k) {
  const n = stones.length;
  if ((n-1) % (k-1) !== 0) return -1;
  const prefix = [0]; for (const s of stones) prefix.push(prefix[prefix.length-1]+s);
  const dp = Array.from({length:n}, ()=>Array(n).fill(0));
  for (let len = k; len <= n; len++)
    for (let i = 0; i+len-1 < n; i++) {
      const j = i+len-1; dp[i][j] = Infinity;
      for (let mid = i; mid < j; mid += k-1)
        dp[i][j] = Math.min(dp[i][j], dp[i][mid]+dp[mid+1][j]);
      if ((len-1)%(k-1)===0) dp[i][j] += prefix[j+1]-prefix[i];
    }
  return dp[0][n-1];
}

Time: O(n² + n³/(k - 1)) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript