Given n ropes of different lengths, connect them into a single rope with minimum cost. Assume that the cost to connect two ropes is the same as the sum of their lengths.

For example,

Input:  [5, 4, 2, 8]
 
Output: The minimum cost is 36
  
[5, 4, 2, 8] –> First, connect ropes of lengths 4 and 2 that will cost 6.
[5, 6, 8]    –> Next, connect ropes of lengths 5 and 6 that will cost 11.
[11, 8]      –> Finally, connect the remaining two ropes that will cost 19.
 
Therefore, the total cost for connecting all ropes is 6 + 11 + 19 = 36.

Practice this problem

The idea is to connect the two lowest-cost ropes first. The resultant rope has a cost equal to the sum of the connected ropes. Repeat the process (with resultant rope included) until we are left with a single rope.

At each iteration of the loop, we will be left with one less rope and the optimal cost is added to the total cost. The final cost for connecting n ropes will be minimal among all possible combinations. A priority queue implemented using min-heap is best suited for this problem. Following is the implementation of this approach in C++, Java, and Python using a min-heap:

C++


Download  Run Code

Output:

The minimum cost is 36

Java


Download  Run Code

Output:

The minimum cost is 36

Python


Download  Run Code

Output:

The minimum cost is 36

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the total number of ropes.