Minimum Cost to Merge Stones

Hard

Topics
ArrayDynamic ProgrammingPrefix Sum

You have nums.length piles of stones arranged in a row; nums[i] is the number of stones in pile i. In one move you merge exactly k consecutive piles into a single pile, and the cost of that move equals the total number of stones in those k piles. Return the minimum total cost to merge all piles into one pile. If it is impossible, return -1.

Example 1

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

Example 2

30214213
Input:  stones = [3,2,4,1], k = 3
Output: -1

Example 3

30214213
Input:  stones = [3,5,1,2,6], k = 3
Output: 25

Constraints

  • 1 <= nums.length <= 30
  • 2 <= k <= 30
  • 1 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Feasibility first. Every merge turns k piles into 1, so each move reduces the pile count by k - 1. Reaching exactly one pile from n is possible only when (n - 1) is divisible by (k - 1) — otherwise return -1 without any search.

The DP needs a non-obvious state. dp[i][j] is the minimum cost to merge the window [i, j] into as few piles as the arithmetic allows — not always one. A window of length L collapses to a single pile exactly when (L - 1) % (k - 1) == 0; otherwise it is stuck at several piles and costs only the merges that were possible inside it.

That is why the split point steps by k - 1 rather than by 1: the left part must be collapsible to one pile for the split to describe a real sequence of moves. And the window total is added only on the lengths that do collapse, because that final merge is the one that pays for the whole window.

Approach

  1. Return -1 unless (n - 1) % (k - 1) == 0.
  2. Build prefix sums so any window total is O(1).
  3. Fill dp by increasing window length, starting at k.
  4. For each window, take the best split with mid stepping by k - 1.
  5. If the window length collapses to one pile, add the window's stone total.

Dry Run

nums = [3,5,1,2,6]   k = 3        (n-1) % (k-1) = 4 % 2 = 0, feasible
prefix sums [0, 3, 8, 9, 11, 17]

  window  len  splits tried (mid, cost)  best  final
  [0,2]   3    (0, 0)                    0     + total 9  = 9
  [1,3]   3    (1, 0)                    0     + total 8  = 8
  [2,4]   3    (2, 0)                    0     + total 9  = 9
  [0,3]   4    (0, 8) (2, 9)             8     stays several piles
  [1,4]   4    (1, 9) (3, 8)             8     stays several piles
  [0,4]   5    (0, 8) (2, 9)             8     + total 17 = 25

answer 25

note [0,3] has length 4, and (4-1) % 2 = 1, so it cannot become one pile -- its
cost is just the 8 earned by merging inside it, with no window total added.

Complexity

  • Time — O(n³ / k): O(n²) windows, each trying O(n / k) split points. At the stated bound of 30 piles this is tiny.
  • Space — O(n²) for the table plus O(n) for the prefix sums.

Common Pitfalls

  • Skipping the feasibility check and letting the DP return a number anyway. Without it, an infeasible input produces a plausible-looking cost.
  • Stepping the split point by 1. Only splits where the left part can itself collapse to one pile correspond to legal move sequences; stepping by k - 1 is what enforces that.
  • Adding the window total to every window. It belongs only to the lengths that actually collapse, and adding it everywhere double-charges the interior merges.
  • Defining dp[i][j] as "cost to merge into one pile" and then needing infinity for every window that cannot. That formulation works but needs a third state dimension for the pile count; the "fewest piles possible" definition folds it away.
  • Greedily merging the k cheapest adjacent piles. Local cheapness does not compose; this is the same trap as Huffman coding looking applicable when it is not, because the merges here must stay contiguous.
  • Forgetting that a single pile is already done, costing 0. The (1-1) % (k-1) == 0 test makes n = 1 feasible and the empty DP returns 0.

Full Solution — all languages

class Solution:
    def mergeStones(self, nums, k):
        stones = nums
        n = len(stones)
        if k < 2 or (n - 1) % (k - 1) != 0:
            return -1
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i + 1] = prefix[i] + stones[i]
        dp = [[0] * n for _ in range(n)]
        for length in range(k, n + 1):
            for i in range(0, n - length + 1):
                j = i + length - 1
                best = float('inf')
                mid = i
                while mid < j:
                    best = min(best, dp[i][mid] + dp[mid + 1][j])
                    mid += k - 1
                dp[i][j] = best
                if (length - 1) % (k - 1) == 0:
                    dp[i][j] += prefix[j + 1] - prefix[i]
        return dp[0][n - 1]
Asked at D. E. Shaw
SensAI
Beta
Tap the mic to stop voice mode