Connect n ropes with minimum cost
Given an array arr[] of rope lengths, connect all ropes into a single rope with the minimum total cost. The cost to connect two ropes is the sum of their lengths.
Input: arr[] = [4, 3, 2, 6]
Output: 29
Explanation: We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation 9 + 6 =15. Total cost is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes.
Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3 (we get two rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.
[Expected Approach] Greedy with Heap - O(n*log(n)) Time and O(n) Space
The idea is to connect the smallest two ropes first, as the lengths of the ropes that are picked early are included more than once in the total cost. This approach is similar to the concept used in Huffman Coding, where the smaller elements are combined earlier, which results in a smaller cost for subsequent operations.
To implement the idea, use a min-heap (priority queue) and push all elements into it. While the heap contains more than one element, repeatedly extract the two smallest values, add them, and insert the sum back into the heap. Maintain a variable to track the total cost, incrementing it by the sum of the extracted values at each step. Once the process is complete, return the total cost.
// Java program for connecting n ropes
// with minimum cost using min-heap
import java.util.PriorityQueue;
class GfG {
public static int minCost(int[] arr) {
// Create a priority queue
// By default, the priority queue is in
// increasing order
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : arr) {
pq.add(num);
}
// Initialize result
int res = 0;
// While size of priority queue is more than 1
while (pq.size() > 1) {
// Extract shortest two ropes from pq
int first = pq.poll();
int second = pq.poll();
// Connect the ropes: update result and
// insert the new rope to pq
res += first + second;
pq.add(first + second);
}
return res;
}
public static void main(String[] args) {
int[] arr = {4, 3, 2, 6};
System.out.println(minCost(arr));
}
}
Comments
Post a Comment