Sub topic 12
Worked Example: Merging Adjacent Piles
This chapter assumes you already know the split-point recurrence, how to fill a table by increasing interval length, and how prefix sums give a range total in O(1). Here those three ideas are combined to solve the classic stone merging problem. The chapter also shows the mistakes people usually make with it.
The Problem
You have n piles of stones in a row. Pile i has weight piles[i]. In one move you pick two adjacent piles and merge them into a single pile. The move costs the weight of the new pile. You keep merging until one pile remains. The goal is the minimum total cost.
Take [4, 1, 1, 4]. Two possible merge orders give different totals:
| Order of merges | Costs paid | Total |
|---|---|---|
| (4,1), then (1,4), then (5,5) | 5 + 5 + 10 | 20 |
| (1,1), then (4,2), then (6,4) | 2 + 6 + 10 | 18 |
The second order is cheaper, and 18 is the optimum. Every order ends with the same final merge of weight 10, which is the total of all piles. The orders differ only in what they pay before that last merge.
Why This Is an Interval Problem
The adjacency rule is what makes this interval DP. Because only neighbors can merge, every pile that exists at any moment is the merged form of a contiguous range of the original piles. Piles 0 and 2 can never combine unless pile 1 goes into the same result.
Now look at the last merge for a range i..j. It joins two piles. One is the merged form of i..k and the other is the merged form of k+1..j, for some split k with i <= k < j. The two sides never interact before that final step, so each side can be solved on its own as a smaller version of the same problem.
The total cost is the sum of the labels on the internal nodes: 10 + 6 + 2 = 18. Another way to see it: each original pile pays its weight once for every internal node above it. That is why the total weight of the range appears in the recurrence.
State, Base Case, and Recurrence
- State.
dp[i][j]is the minimum cost to merge pilesithroughj, both inclusive, into one pile. - Base case.
dp[i][i] = 0, because a single pile needs no merges. - Recurrence. For
i < j:
dp[i][j] = min over k in [i, j-1] of ( dp[i][k] + dp[k+1][j] ) + sum(i..j)The term sum(i..j) does not depend on k. It is the cost of the final merge, and that merge always produces a pile of the whole range's weight. You can therefore take the minimum over k first and add the sum once afterward. With a prefix array, sum(i..j) is prefix[j+1] - prefix[i].
The answer is dp[0][n-1].
Implementation
def min_merge_cost(piles):
n = len(piles)
if n <= 1:
return 0
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
best = min(dp[i][k] + dp[k + 1][j] for k in range(i, j))
dp[i][j] = best + prefix[j + 1] - prefix[i]
return dp[0][n - 1]
print(min_merge_cost([4, 1, 1, 4])) # 18
print(min_merge_cost([3, 2, 2, 3])) # 20The outer loop runs over length. Every dp[i][k] and dp[k+1][j] covers a strictly shorter range than i..j, so it was filled in an earlier pass. The table starts as all zeros, which already sets the base cases.
Tracing the Table
Here is every entry for [4, 1, 1, 4] (prefix = [0, 4, 5, 6, 10]):
| Range | Sum | Candidates `dp[i][k] + dp[k+1][j]` | Best | `dp` |
|---|---|---|---|---|
| 0..1 | 5 | k=0: 0+0 | 0 | 5 |
| 1..2 | 2 | k=1: 0+0 | 0 | 2 |
| 2..3 | 5 | k=2: 0+0 | 0 | 5 |
| 0..2 | 6 | k=0: 0+2=2, k=1: 5+0=5 | 2 | 8 |
| 1..3 | 6 | k=1: 0+5=5, k=2: 2+0=2 | 2 | 8 |
| 0..3 | 10 | k=0: 0+8=8, k=1: 5+5=10, k=2: 8+0=8 | 8 | 18 |
Two splits tie for the full range. Split k=0 merges [1,1,4] first and then adds the left 4. Split k=2 is the mirror image. Both cost 18.
Recovering the Merge Order
To see which merges produce the optimum, store the best k the same way as in matrix chain multiplication, then walk the split table recursively.
def min_merge_plan(piles):
n = len(piles)
prefix = [0] * (n + 1)
for i, p in enumerate(piles):
prefix[i + 1] = prefix[i] + p
dp = [[0] * n for _ in range(n)]
split = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = float("inf")
for k in range(i, j):
cost = dp[i][k] + dp[k + 1][j]
if cost < dp[i][j]:
dp[i][j] = cost
split[i][j] = k
dp[i][j] += prefix[j + 1] - prefix[i]
return dp[0][n - 1], split
def render(piles, split, i, j):
if i == j:
return str(piles[i])
k = split[i][j]
return "(" + render(piles, split, i, k) + " + " + render(piles, split, k + 1, j) + ")"
piles = [4, 1, 1, 4]
cost, split = min_merge_plan(piles)
print(cost) # 18
print(render(piles, split, 0, len(piles) - 1)) # (4 + (1 + (1 + 4)))The strict < keeps the first minimum it finds, so the tie at range 0..3 goes to k=0. Inside 1..3 the tie goes the same way. The printed plan merges (1,4), then (1,5), then (4,6), for costs 5 + 6 + 10 = 21? That is wrong, so check against the table. Range 1..3 has k=1 with cost 5 and k=2 with cost 2. The strict comparison picks k=2, the true minimum, so the output is (4 + ((1 + 1) + 4)), and that plan costs 2 + 6 + 10 = 18. When you trace by hand, always read the minimum from the table instead of guessing which tie wins.
Common Errors
Using a Greedy Rule
A tempting greedy rule is to always merge the adjacent pair with the smallest sum. It fails on [3, 2, 2, 3]. Greedy merges (2,2) for 4, then (3,4) for 7, then the final 10, for a total of 21. The DP finds (3,2) for 5, (2,3) for 5, then 10, for a total of 20.
Adding the Range Sum in the Wrong Place
Some versions add sum(i..k) + sum(k+1..j) inside the min, or add the sum to each child as well as the parent. The children's costs already include everything paid inside them. The parent pays only for its own final merge, which is the range sum, added once.
Misreading the Bounds
If dp[i][j] is inclusive, the split runs over k in range(i, j), and the right part starts at k + 1. Using range(i, j + 1) lets k = j, which creates an empty right side. Here that reads dp[j+1][j], which is either out of bounds or a zero that should not exist.
Iterating `i` Upward without a Length Loop
Filling rows with i going up and j going up reads dp[k+1][j] before that row is filled. Either loop by length, as above, or loop i downward from n-1 and j upward from i+1.
Testing Against Brute Force
For small inputs you can try every merge sequence and compare. Put this in the same file as min_merge_cost:
import random
from functools import lru_cache
def brute_force(piles):
@lru_cache(maxsize=None)
def go(state):
if len(state) == 1:
return 0
best = float("inf")
for t in range(len(state) - 1):
merged = state[t] + state[t + 1]
nxt = state[:t] + (merged,) + state[t + 2:]
best = min(best, merged + go(nxt))
return best
return go(tuple(piles))
for _ in range(300):
piles = [random.randint(1, 9) for _ in range(random.randint(1, 7))]
assert min_merge_cost(piles) == brute_force(piles), piles
print("all tests passed")The brute force grows exponentially with n, so keep n at 7 or below.
Cost
There are O(n²) states, and each one scans up to n splits, so the time is O(n³) and the space is O(n²). The prefix sums keep the range-sum term at O(1). Without them, each state would pay an extra O(n) to compute its sum, which leaves the O(n³) bound unchanged but adds wasted work. Later chapters show how a circular row of piles is handled by doubling the array, and how Knuth's optimization narrows the split scan to bring this exact recurrence down to O(n²).
Exercise
Fill the DP table by hand for piles [1, 3, 2]. What is the minimum total cost, and which pair is merged first?
Show answer
dp[0][1] = 4 and dp[1][2] = 5. For 0..2 the sum is 6. Split k=0 gives 0 + 5 = 5 and k=1 gives 4 + 0 = 4, so dp[0][2] = 4 + 6 = 10. The first merge is (1, 3) for 4, then (4, 2) for 6, for a total of 10.
Exercise
Suppose the goal changes to the maximum total cost instead of the minimum. What changes in minmergecost, and what is the answer for [4, 1, 1, 4]?
Show answer
Replace min with max over k. The base case and the added range sum stay the same. For [4, 1, 1, 4] the length-3 ranges each get max(5, 2) + 6 = 11. The full range then gets max(0 + 11, 5 + 5, 11 + 0) + 10 = 21, for example by merging (4,1), then (5,1), then (6,4).
Exercise
Explain why the range sum is added outside the min over k instead of inside it, and whether moving it inside would change the result.
Show answer
The range sum is the weight of the pile made by the final merge, and that weight is the same for every split k. Moving it inside the min gives the same value, because adding a constant to every candidate does not change which one is smallest. It just repeats the addition for every k. The real bug would be adding the children's sums as well, which double-counts costs the children already include.