Skip to main content

Minimum Cost to Connect Sticks

MediumPremium

You have some sticks with positive integer lengths, given as the array sticks. You can join any two sticks of lengths x and y into one stick of length x + y, which costs x + y. Keep joining until one stick is left.

Return the lowest total cost to join all the sticks into one.

Example 1

Input: sticks = [2, 4, 3] Output: 14

Join 2 and 3 for a cost of 5, leaving [5, 4]. Then join 5 and 4 for a cost of 9. The total is 14.

Example 2

Input: sticks = [1, 8, 3, 5] Output: 30

Constraints

  • 1 <= sticks.length <= 10000
  • 1 <= sticks[i] <= 10000