Menu
CoddyTech

Minimum Cost of Ropes

EasyHeapGreedypython iconjava iconcpp iconc iconjs icon+10

You have some ropes, and ropes[i] is the length of rope i. You can join any two ropes into one rope whose length is the sum of the two, and that join costs the same sum. You keep joining until a single rope is left.

Write a function named minCostRopes that returns the smallest total cost of joining all the ropes into one, or 0 when there is only one rope to begin with.

Function

minCostRopes(ropes: integer-array) → integer
ropesinteger-array
the length of each rope
Returnsinteger
the smallest total cost of joining every rope into one

Constraints

  • 1 ≤ ropes.length ≤ 104
  • 1 ≤ ropes[i] ≤ 100
  • The answer fits in a 32-bit signed integer.

Examples

Input
ropes = [5, 2, 8, 3]
Output
33
Explanation
Join 2 and 3 for 5, the two ropes of length 5 for 10, then 8 and 10 for 18. The total is 5 + 10 + 18 = 33.
challenge icon

Follow-up

Suppose a join may tie up to three ropes and costs their total length. How does the greedy rule change when the number of ropes does not work out evenly?

Reset code
def minCostRopes(ropes):
    # Write code here

Test #1

Test #2

Test #3

Argument

ropes = [5, 2, 8, 3]

Expected Output

33