Connect n ropes with minimum cost

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
CodingNinjas
author
2y
Brute Force 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 s...read more

CodingNinjas
author
2y
Heap 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...read more
Help your peers!
Add answer anonymously...
SpeedLabs Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter