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 the sum of any range in O(1). Here those three ideas come together in one problem.
The Problem
You have a row of piles with weights piles[0..n-1]. In one step you merge two adjacent piles into one pile. The cost of that step is the combined weight of the new pile. You keep merging until only one pile is left. Find the minimum total cost.
The adjacency rule matters. If any two piles could be merged, a greedy Huffman-style approach would work. Because only neighbors can merge, every pile you ever create covers a contiguous range of the original row. That is the signal to use interval DP.
Defining the State
Let dp[i][j] be the minimum cost to merge piles i..j (inclusive) into a single pile.
- Base case:
dp[i][i] = 0. A single pile needs no merging. - Answer:
dp[0][n-1].
The Recurrence
Look at the final merge for the range i..j. Just before it, two piles remain: one built from i..k and one built from k+1..j, for some split k with i <= k < j. The final merge always costs the full weight of i..j, whatever k is:
dp[i][j] = min over k in [i, j-1] of (dp[i][k] + dp[k+1][j]) + sum(i..j)The sum(i..j) term does not depend on k, so you add it once, outside the minimum. With prefix sums, sum(i..j) = prefix[j+1] - prefix[i].
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])) # 18Tracing the Table
For [4, 1, 1, 4], the table fills one interval length at a time:
| Interval | Best split | min(dp[i][k] + dp[k+1][j]) | sum | dp |
|---|---|---|---|---|
| [0,1] | k=0 | 0 | 5 | 5 |
| [1,2] | k=1 | 0 | 2 | 2 |
| [2,3] | k=2 | 0 | 5 | 5 |
| [0,2] | k=0 | 0 + 2 = 2 | 6 | 8 |
| [1,3] | k=2 | 2 + 0 = 2 | 6 | 8 |
| [0,3] | k=0 or k=2 | 8 | 10 | 18 |
Splitting down the middle (k=1) gives 5 + 5 + 10 = 20. That looks balanced, but it is not optimal. The DP tries every split, so it finds 18.
Common Errors
- Merging non-adjacent piles in your head. If the problem lets any two piles merge, this is a different problem, and a min-heap solves it greedily.
- Setting the base case to the pile's weight. A single pile costs 0. Its weight is only counted when it takes part in a merge.
- Filling by
ithenjin increasing order.dp[k+1][j]has a largerithan the cell you are computing, so it would not be ready yet. Loop over length, or loopidownward.
The algorithm runs in O(n³) time and uses O(n²) space. Later chapters show how to handle a circular row of piles and how Knuth's optimization reduces the time to O(n²).
Exercise
What is the minimum merge cost for piles [3, 2, 4]? Give dp[0][1], dp[1][2], and dp[0][2].
Show answer
dp[0][1] = 5 and dp[1][2] = 6. For dp[0][2], split k=0 gives 0 + 6 = 6 and split k=1 gives 5 + 0 = 5. The minimum is 5, and adding the total 9 gives dp[0][2] = 14.
Exercise
Why can the interval sum be added outside the min over k instead of inside it?
Show answer
The final merge of i..j always produces a pile whose weight is the sum of piles i..j, whichever split k comes before it. The term is the same for every k, so it cannot change which k is smallest.