Greedy Algorithms8 sections · 316 units
Open in Course

Connect Sticks - Implementation

The code

Here is the solution:

function connectSticks(sticks)
 heap := min-heap of sticks
 cost := 0
 while heap.size > 1
 a := heap.pop()
 b := heap.pop()
 merged := a + b
 cost := cost + merged
 heap.push(merged)
 return cost

Time: O(nlogn)O(n \log n). Space: O(n)O(n).

A min-heap efficiently gives you the two smallest sticks. Merge them, add to cost, push the result back.