Heaps Simulating with a heap
417. Connect Ropes at Minimum Cost
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]
45Explanation: 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]
0Explanation: There is only one rope, so no join happens.
Example 3
Input: ropes = [1000000000, 1000000000, 1000000000]
5000000000Explanation: 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.
Constraints
1 ≤ ropes.length ≤ 1051 ≤ ropes[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.