You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the i-th stick.
You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way. If there is only one stick, no connection is needed and the cost is 0.
Function Signature
def connect_sticks_cost(sticks: list[int]) -> int:
Constraints
-
1 <= len(sticks) <= 10^4
-
1 <= sticks[i] <= 10^4
Examples
Input: sticks = [2,4,3]
Output: 14
Combine 2 and 3 for a cost of 5, then combine 5 and 4 for a cost of 9. The total is 5 + 9 = 14. Any other first merge (2 with 4, or 3 with 4) leads to a total of 15 or 16.
Input: sticks = [1,8,3,5]
Output: 30
Combine 1 and 3 for 4, then 4 and 5 for 9, then 9 and 8 for 17. The total is 4 + 9 + 17 = 30.
Input: sticks = [5]
Output: 0
There is already one stick, so no connection is made.