Connect N Ropes With Minimum Cost
Posted: 28 Jul, 2020
Difficulty: Easy
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.
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
Approach 1
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.
Approach 2
The idea is to use a Heap Data Structure which extracts minimum value in Log(N) time.
Here is the complete algorithm:
- Create a min-heap from all the lengths of ropes.
- Iterate till the number of elements in the min-heap is greater than one.
- Extract the smallest two ropes from the min-heap
- Connect these two extracted ropes and insert the new rope formed back into the min-heap.
- Keep incrementing the ‘finalCost’ by the sum of lengths of the extracted ropes.
- Return the ‘finalCost’.
SIMILAR PROBLEMS
Next Greater Element - I
Posted: 26 Dec, 2021
Difficulty: Moderate
Preorder Traversal
Posted: 18 Jan, 2022
Difficulty: Easy
Inorder Traversal
Posted: 19 Jan, 2022
Difficulty: Easy
Postorder Traversal
Posted: 20 Jan, 2022
Difficulty: Easy
Min Stack
Posted: 22 Jan, 2022
Difficulty: Easy