05. Minimum Cost to Merge Stones

Difficulty:HardPattern:Interval Dynamic ProgrammingTime:O(n^3 / k)Space:O(n^2)

There are n piles of stones arranged in a row. A move consists of merging exactly k consecutive piles into one pile. Return the minimum cost to merge all piles into one pile.

How It Works & Algorithmic Design

Solves using Interval Dynamic Programming with Pile Group Reductions:

  1. Feasibility Check: Return -1 if (n - 1) % (k - 1) !== 0.
  2. Prefix Sums: pref[i] to quickly compute pile segment sums.
  3. DP State: dp[i][j] = minimum cost to merge piles i...j into as few piles as possible.
  4. Interval Expansion Loop (len from k to n):
    • Step split point m from i to j-1 with stride k-1:
      • dp[i][j] = Math.min(dp[i][j], dp[i][m] + dp[m+1][j]).
    • If piles i...j can be merged down to 1 pile ((j - i) % (k - 1) === 0):
      • dp[i][j] += pref[j+1] - pref[i].

Why This Approach Works Best

Interval DP systematically evaluates sub-pile combination choices in $O(n^3 / k)$ time.

Example Walkthrough

Input

stones = [3, 5, 1, 2, 6], k = 3

5 stone piles, merge 3 at a time.

Feasibility

(5 - 1) % (3 - 1) = 0 -> valid merge configuration.

Possible to merge to 1 pile.

Output

25

Minimum merge cost.

Answer: Minimum Cost to Merge Stones implementation

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

Interval dynamic programming evaluating consecutive sub-pile merges.

Key Takeaways
  • Modulo feasibility check (n - 1) % (k - 1) === 0 validates if complete reduction is possible.

  • Step loop variable m by k - 1 to skip invalid pile split states.

  • Interval DP executes in $O(n^3 / k)$ time.