The Minimum Cost to Connect Sticks problem gives you several sticks of different lengths. You can connect two sticks into one by paying a cost equal to the sum of their lengths. You repeat this until only one stick remains. The goal is to find the minimum total cost to connect all the sticks.
This is a classic Minimum Cost to Connect Sticks interview question at Amazon and J.P. Morgan. It is the same underlying problem as Huffman Coding. It tests if a candidate understands that to minimize the total sum, the smallest values should be combined as many times as possible (i.e., they should be deeper in the "combination tree").
The Greedy with Heap (Priority Queue) interview pattern is the optimal solution.
a and b.a + b.a + b back into the heap.Sticks: [2, 4, 3].
[2, 3, 4].2 and 3: Cost = 5. New heap: [4, 5]. Total cost = 5.4 and 5: Cost = 9. New heap: [9]. Total cost = 5 + 9 = 14.
If we connected 4 and 3 first (7), then 7 and 2 (9), the total would be 7 + 9 = 16, which is higher.Whenever you have a problem that involves "repeatedly combining the two smallest/largest elements," immediately think of a Priority Queue. This is the standard way to maintain a sorted set of elements where values are constantly changing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximal Score After Applying K Operations | Medium | Solve | |
| Maximum Average Pass Ratio | Medium | Solve | |
| Make the Prefix Sum Non-negative | Medium | Solve | |
| Maximum Product After K Increments | Medium | Solve | |
| Remove Stones to Minimize the Total | Medium | Solve |