Minimum Cost to Connect Sticks

Given an array sticks where sticks[i] is the length of the ith stick, connect all sticks into one stick. Each time you connect two sticks with lengths x and y, the cost is x + y. Return the minimum cost to connect all sticks. Pattern focus: Greedy Scheduling. Always connect the two shortest sticks first, which is best handled with a min-heap.

Input Format

sticks = lengths of sticks

Output Format

minimum total cost

Constraints

  • 1 <= sticks.length <= 10^5
  • 1 <= sticks[i] <= 10^9

Examples

Example 1:

Input:

sticks = [2,4,3]

Output:

14

Explanation:

Connect 2 and 3 (cost 5), then connect 4 and 5 (cost 9), total 14.

Example 2:

Input:

sticks = [1,8,3,5]

Output:

30

Explanation:

The cheapest merges are always between the two shortest available sticks.

Example 3:

Input:

sticks = [5]

Output:

0

Explanation:

Only one stick exists, so no connection is needed.

Loading...
Minimum Cost to Connect Sticks - Greedy