712258. Minimum Cost to Merge Stones
Minimum Cost to Merge Stones
Slug: minimum-cost-to-merge-stones
Difficulty: Hard
Topic Tags: Dynamic Programming, Algorithms
Company Tags: None
Summary
The problem is about merging stones in a river. You are given an array of integers representing the costs of removing each stone from the river. The goal is to find the minimum cost required to remove all stones such that no two adjacent stones are removed. The solution involves dynamic programming, where we keep track of the minimum cost at each step and choose the optimal approach.
Detailed Explanation
The problem can be broken down into a simple dynamic programming approach. Let dp[i] be the minimum cost to merge stones from index 0 to i. We have two options:
- Remove stone at index i: In this case, we need to remove the previous stone as well (since no two adjacent stones are removed). The cost is
cost[i] + dp[i-2]. - Do not remove stone at index i: In this case, we can consider merging stones from index 0 to i-1. The cost is simply
dp[i-1].
We choose the option that results in the minimum cost and update dp[i]. The final answer is dp[n-1], where n is the number of stones.
Here's a step-by-step breakdown:
- Initialize an array
dpwith sizen+1and setdp[0] = 0. - Iterate through the array from index 2 to
n. For each indexi, calculate the minimum cost using the two options above. - Update
dp[i]with the minimum cost. - The final answer is
dp[n-1].
Time complexity: O(n) Space complexity: O(n)
Optimized Solutions
Java
public class MinimumCostToMergeStones {
public static int minCost(int[] stones) {
int n = stones.length;
int[] dp = new int[n+1];
dp[0] = 0;
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(stones[i-1] + dp[i-2], dp[i-1]);
}
return dp[n-1];
}
}