 All Problems
Minimum Cost to Connect Sticks
medium
greedy
heap
array
amazon
google

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 ith stick.

You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You perform this action until there is one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

Example 1:

Input:  2 4 3
Output: 14

(2+3=5, then 5+4=9 → total 14)

Example 2:

Input:  1 8 3 5
Output: 30

Constraints:

  • 1 ≤ sticks.length ≤ 10⁴
  • 1 ≤ sticks[i] ≤ 10⁴

Input format: Space-separated integers.

Output format: Minimum total cost.

Run to check your code against the sample cases, or submit to run every case