Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Minimum Cost to Connect Sticks

Huffman-like merging

You have sticks of various lengths. To connect two sticks, the cost is the sum of their lengths. Connect all sticks into one with minimum cost.

For sticks=[2,4,3]sticks = [2,4,3]: connect 2+3=52+3=5 (cost 55), then 5+4=95+4=9 (cost 99). Total cost 1414. Or: 2+4=62+4=6 (cost 66), then 6+3=96+3=9 (cost 99). Total cost 1515. The first way is better.

Constraint: you can only connect two sticks at a time. Each merge produces a new stick whose length is the sum. Order matters: merging small sticks early keeps costs low.