05. Minimum Cost to Merge Stones
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:
- Feasibility Check: Return
-1if(n - 1) % (k - 1) !== 0. - Prefix Sums:
pref[i]to quickly compute pile segment sums. - DP State:
dp[i][j]= minimum cost to merge pilesi...jinto as few piles as possible. - Interval Expansion Loop (
lenfromkton):- Step split point
mfromitoj-1with stridek-1:dp[i][j] = Math.min(dp[i][j], dp[i][m] + dp[m+1][j]).
- If piles
i...jcan be merged down to 1 pile ((j - i) % (k - 1) === 0):dp[i][j] += pref[j+1] - pref[i].
- Step split point
Why This Approach Works Best
Interval DP systematically evaluates sub-pile combination choices in $O(n^3 / k)$ time.
Example Walkthrough
stones = [3, 5, 1, 2, 6], k = 3
5 stone piles, merge 3 at a time.
(5 - 1) % (3 - 1) = 0 -> valid merge configuration.
Possible to merge to 1 pile.
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.
Modulo feasibility check
(n - 1) % (k - 1) === 0validates if complete reduction is possible.Step loop variable
mbyk - 1to skip invalid pile split states.Interval DP executes in $O(n^3 / k)$ time.