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
The task is to connect N ropes into one rope with minimum cost.
Sort the array of rope lengths in ascending order.
Initialize a variable to keep track of the total cost.
While there are more than one rop...read more
I tried it with a min-heap and insert all lengths into the min-heap. Extract the minimum and second minimum from min-heap. Add the above two extracted values and insert the added value to the min-heap...read more
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 s...read more
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...read more
Top Paytm SDE-2 interview questions & answers
Popular interview questions of SDE-2
Reviews
Interviews
Salaries
Users/Month