Minimum Cost to Merge Stones
Hard
Topics
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
Input: stones = [3,2,4,1], k = 2 Output: 20
Example 2
Input: stones = [3,2,4,1], k = 3 Output: -1
Example 3
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
- Return -1 unless
(n - 1) % (k - 1) == 0. - Build prefix sums so any window total is O(1).
- Fill
dpby increasing window length, starting atk. - For each window, take the best split with
midstepping byk - 1. - 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 - 1is 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
kcheapest 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) == 0test makesn = 1feasible 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]import java.util.*;
class Solution {
public int mergeStones(int[] nums, int k) {
int[] stones = nums;
int n = stones.length;
if (k < 2 || (n - 1) % (k - 1) != 0) return -1;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + stones[i];
int[][] dp = new int[n][n];
for (int length = k; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
int best = Integer.MAX_VALUE;
for (int mid = i; mid < j; mid += k - 1) best = Math.min(best, dp[i][mid] + dp[mid + 1][j]);
dp[i][j] = best;
if ((length - 1) % (k - 1) == 0) dp[i][j] += prefix[j + 1] - prefix[i];
}
}
return dp[0][n - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int mergeStones(vector<int>& nums, int k) {
vector<int>& stones = nums;
int n = stones.size();
if (k < 2 || (n - 1) % (k - 1) != 0) return -1;
vector<int> prefix(n + 1, 0);
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + stones[i];
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int length = k; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
int best = INT_MAX;
for (int mid = i; mid < j; mid += k - 1) best = min(best, dp[i][mid] + dp[mid + 1][j]);
dp[i][j] = best;
if ((length - 1) % (k - 1) == 0) dp[i][j] += prefix[j + 1] - prefix[i];
}
}
return dp[0][n - 1];
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/ var mergeStones = function(nums, k) {
const stones = nums, n = stones.length;
if (k < 2 || (n - 1) % (k - 1) !== 0) return -1;
const prefix = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) prefix[i + 1] = prefix[i] + stones[i];
const dp = [];
for (let i = 0; i < n; i++) dp.push(new Array(n).fill(0));
for (let length = k; length <= n; length++) {
for (let i = 0; i + length - 1 < n; i++) {
const j = i + length - 1;
let best = Infinity;
for (let mid = i; mid < j; mid += k - 1) best = Math.min(best, dp[i][mid] + dp[mid + 1][j]);
dp[i][j] = best;
if ((length - 1) % (k - 1) === 0) dp[i][j] += prefix[j + 1] - prefix[i];
}
}
return dp[0][n - 1];
};