#1000

Minimum Cost to Merge Stones

Hard
ArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n³)
Space
O(1)
O(n²)
💡

Intuition

Time O(n³)Space O(n²)

The optimal approach uses dynamic programming to minimize the cost of merging stones. By storing the results of subproblems, we avoid redundant calculations and efficiently find the minimum cost.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a DP table to store minimum costs for merging stones from index i to j.
  2. 2Step 2: Use prefix sums to calculate the total stones in any range quickly.
  3. 3Step 3: Iterate through possible lengths of merges and calculate costs based on previous results in the DP table.
  4. 4Step 4: Return the minimum cost to merge all stones into one pile.
solution.py18 lines
1def mergeStones(stones, k):
2    n = len(stones)
3    if (n - 1) % (k - 1) != 0:
4        return -1
5    dp = [[float('inf')] * n for _ in range(n)]
6    prefix_sum = [0] * (n + 1)
7    for i in range(n):
8        prefix_sum[i + 1] = prefix_sum[i] + stones[i]
9    for length in range(k, n + 1):
10        for i in range(n - length + 1):
11            j = i + length - 1
12            if length == k:
13                dp[i][j] = prefix_sum[j + 1] - prefix_sum[i]
14            else:
15                for m in range(i, j, k - 1):
16                    dp[i][j] = min(dp[i][j], dp[i][m] + dp[m + 1][j])
17                dp[i][j] += prefix_sum[j + 1] - prefix_sum[i]
18    return dp[0][n - 1]

Complexity note: The time complexity is O(n³) because we are iterating through all possible lengths and combinations of merges, leading to a cubic growth in operations. The space complexity is O(n²) due to the DP table storing results for each subproblem.

  • 1Merging is only possible if the remaining piles can be merged into one.
  • 2Dynamic programming helps in breaking down the problem into manageable subproblems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.