Last Updated: 28 Jul, 2020

Connect N Ropes With Minimum Cost

Easy
Asked in companies
ArcesiumUberOptum

Problem statement

You have been given 'N' ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. We need to connect the ropes with minimum cost.

The test-data is such that the result will fit into a 32-bit integer.

Input format :

The first line of input contains an integer value 'N'. It denotes the total number of ropes.

The second line of input contains 'N' single space separated integers representing length of each rope i.e. a1, a2, a3, ... an.

Output Format :

The only line of output will contain an integer, the minimum cost for connecting all the ropes.

Note:

You need not to print anything, it has been already taken care of. Just implement the given function.

Constraints :

1 <= N <= 10^5
1 <= ai <= 10^9

Time Limit : 1 sec

Approaches

01 Approach

Clearly, the rope which is picked up first will be having its length included more than once in the final cost. If we pick a rope of larger length earlier, then we will be adding some extra cost to our final result.
So, the idea is to pick ropes of smaller lengths initially to minimize the impact on our final cost.

So, each time we will be finding two smallest ropes, connecting them and

adding the resulting rope back to the pile.

02 Approach

The idea is to use a Heap Data Structure which extracts minimum value in Log(N) time.

Here is the complete algorithm:

  1. Create a min-heap from all the lengths of ropes.
  2. Iterate till the number of elements in the min-heap is greater than one.
    1. Extract the smallest two ropes from the min-heap
    2. Connect these two extracted ropes and insert the new rope formed back into the min-heap.
    3. Keep incrementing the ‘finalCost’ by the sum of lengths of the extracted ropes.
  3. Return the ‘finalCost’.