Minimum Cost to Merge Stone Piles
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests interval DP by finding the minimum total cost to merge an array of stone piles into one, where merging any contiguous segment costs the sum of that segment.
Minimum Cost to Merge Stone Piles
You are given a row of n stone piles. Each pile has a positive integer weight. You may repeatedly pick any contiguous subarray of the current sequence and merge it into a single pile whose weight equals the sum of the merged piles. The cost of one merge operation is the sum of the weights being merged.
Your goal is to merge all piles into a single pile with the minimum total cost.
Note: unlike some restricted variants, you may merge any number of contiguous piles at once (not just exactly two), so a solution always exists for any input.
Constraints
1 <= n <= 3001 <= piles[i] <= 1000- Merging a single pile into itself (a trivial sub-problem of size 1) costs
0. - The answer is always a non-negative integer.
Examples
Example 1
Input: min_merge_cost([3, 2, 4, 1])
Output: 20
Example 2
Input: min_merge_cost([1])
Output: 0
Example 3
Input: min_merge_cost([5, 5, 5, 5, 5])
Output: 60
Hints
Hint 1
Build a prefix sum array so the cost of merging piles[i..j] can be computed in O(1) as prefix[j+1] - prefix[i].
Hint 2
Define dp[i][j] as the minimum total cost to reduce piles[i..j] to a single pile. The base case is dp[i][i] = 0.
Hint 3
For each interval [i, j], try every split point k in [i, j-1]: dp[i][j] = min over k of (dp[i][k] + dp[k+1][j] + cost(i, j)), because no matter how you merge sub-intervals, the final merge that combines the left and right halves always costs the sum of the whole interval.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
No matter how you break the problem into sub-merges, the last operation that combines the left and right parts of an interval [i, j] always costs exactly sum(piles[i..j]) — the total weight of the whole interval. This is because by the time you perform that final merge, the two halves have each been reduced to a single pile whose combined weight is the original sum.
Therefore, if we define:
dp[i][j]= minimum total cost to reducepiles[i..j]to one pile
Then:
dp[i][j] = min over k in [i, j-1] of:
dp[i][k] + dp[k+1][j] + sum(piles[i..j])
dp[i][k]: best cost to collapse the left sub-intervaldp[k+1][j]: best cost to collapse the right sub-intervalsum(piles[i..j]): the inevitable cost of the final merge
Base case: dp[i][i] = 0 (a single pile needs no merging).
Why It Is Correct
The recurrence exhausts every way to make the last split that separates the interval into two contiguous parts. Because the final merge cost is fixed (the full range sum) regardless of the split, we only need to minimize the sub-problem costs. Filling the table in increasing order of interval length ensures all smaller sub-problems are already solved when needed.
Prefix Sums
We precompute prefix sums so that sum(piles[i..j]) is answered in O(1), making the overall algorithm efficient.
Complexity
- Time: O(n³) — O(n²) intervals, each with O(n) split points.
- Space: O(n²) for the DP table, O(n) for prefix sums.
For n ≤ 300, this is approximately 27 million operations — comfortably fast.
from typing import List
def min_merge_cost(piles: List[int]) -> int:
n = len(piles)
if n <= 1:
return 0
# Prefix sums for O(1) range sum queries
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + piles[i]
def range_sum(i, j):
return prefix[j + 1] - prefix[i]
# dp[i][j] = min cost to merge piles[i..j] into one pile
dp = [[0] * n for _ in range(n)]
# Fill by increasing interval length
for length in range(2, n + 1): # length of interval
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = float('inf')
cost = range_sum(i, j) # final merge always costs full sum
for k in range(i, j): # try every split
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + cost)
return dp[0][n - 1]