KatInterview

Minimum Cost to Merge Stone Piles

Dynamic ProgrammingAuto-graded · 17 test cases
HardAuto-gradedDynamic Programmingdynamic programminginterval DPmemoization

Last 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 <= 300
  • 1 <= 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.