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,

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’re left with a single rope.
At each iteration of the loop, we’ll 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

Download   Run Code
Output:

The minimum cost is 36

Download   Run Code
Output:

The minimum cost is 36

Download   Run Code
Output:

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

source