Minimum Cost to Connect Sticks - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
sticks = [2,4,3]
›
Output:
14
💡 Note:
Combine 2+3=5 (cost 5), then combine 5+4=9 (cost 9). Total cost = 5+9 = 14
Example 2 — Four Sticks
$
Input:
sticks = [1,8,3,5]
›
Output:
30
💡 Note:
Optimal: 1+3=4 (cost 4), 4+5=9 (cost 9), 8+9=17 (cost 17). Total cost = 4+9+17 = 30
Example 3 — Single Stick
$
Input:
sticks = [20]
›
Output:
0
💡 Note:
Only one stick, no combining needed, so cost is 0
Constraints
- 1 ≤ sticks.length ≤ 104
- 1 ≤ sticks[i] ≤ 104
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code