oneby7

Heaps Simulating with a heap

417. Connect Ropes at Minimum Cost

Easy

You are given an array ropes, where ropes[i] is the length of the i-th rope. You want to join all of them into one rope.

You join ropes two at a time. Joining a rope of length a and a rope of length b costs a + b and gives one rope of length a + b, which can be joined again later. In each step you may join any two ropes you have.

Return the smallest total cost of joining all the ropes into one. With a single rope there is nothing to join, so the answer is 0.

Example 1

Input: ropes = [6, 2, 4, 9, 1]

Output: 45

Explanation: Join 1 and 2 into 3, then 3 and 4 into 7, then 6 and 7 into 13, and finally 9 and 13 into 22. The joins cost 3 + 7 + 13 + 22 = 45.

Example 2

Input: ropes = [1000000000]

Output: 0

Explanation: There is only one rope, so no join happens.

Example 3

Input: ropes = [1000000000, 1000000000, 1000000000]

Output: 5000000000

Explanation: The first join costs 2000000000. The new rope is then joined to the last one, which costs 3000000000.

Check your understanding

Work out the answer for this input before you write any code.

ropes = [5, 2, 8, 3]

Constraints

  • 1 ≤ ropes.length ≤ 105
  • 1 ≤ ropes[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.