Minimum Cost to Connect Sticks
Master this topic with zero to advance depth.
Minimum Cost to Connect Sticks
You have sticks with positive integer lengths. You can connect any two sticks into one by paying a cost equal to their sum. Return the minimum cost to connect all sticks.
Visual Representation
Sticks: [2, 4, 3]
1. Combine 2 and 3: Cost = 5. Remaining: [5, 4]
2. Combine 5 and 4: Cost = 9. Remaining: [9]
Total: 14Examples
Combining 2+3 first followed by 4 is cheaper than other combinations.
Level I: Brute Force (Try All Pairs)
Intuition
Try every possible sequence of connecting two sticks and find the one that results in the minimum total cost. This can be implemented using recursion by trying all pairs at each step.
Thought Process
- If only 1 stick remains, return 0.
- For every pair of sticks :
- Combine them:
cost = sticks[i] + sticks[j]. - Recursively solve for the new set of sticks.
- Track the minimum total cost across all possible initial pairs.
- Combine them:
Detailed Dry Run
sticks = [2, 4, 3]
- Option 1: (2,4) -> [6,3]. Then (6,3) -> [9]. Cost = 6 + 9 = 15.
- Option 2: (2,3) -> [5,4]. Then (5,4) -> [9]. Cost = 5 + 9 = 14. (MIN)
- Option 3: (4,3) -> [7,2]. Then (7,2) -> [9]. Cost = 7 + 9 = 16.
Level II: Sorting and Re-sorting
Intuition
At each step, we identify the two smallest sticks by sorting the list, combine them, and repeat. While better than brute force, re-sorting at every step is inefficient.
Thought Process
- While more than 1 stick exists:
- Sort the current list of sticks.
- Take the two smallest elements, sum them.
- Add the sum to
totalCost, remove the two elements, and add the sum back.
- Repeat until 1 stick remains.
Detailed Dry Run
sticks = [2, 4, 3]
- Sort: [2, 3, 4]. Combine 2+3=5. Total=5. Sticks: [5, 4]
- Sort: [4, 5]. Combine 4+5=9. Total=14. Sticks: [9] Result: 14
Level III: Optimal Greedy (Min-Heap)
Intuition
To minimize the total cost, we should always combine the two smallest sticks currently available. This is the Huffman Coding principle.
Thought Process
- Add all sticks to a Min-Heap.
- While
heap.size() > 1:- Pop
s1ands2(two smallest). cost = s1 + s2.totalCost += cost, Pushcostback to heap.
- Pop
Pattern: Huffman Coding (Greedy Merging)
Detailed Dry Run
Sticks: [1, 8, 3, 5]
- Pop 1, 3. Sum = 4. Total = 4. Heap: [4, 5, 8]
- Pop 4, 5. Sum = 9. Total = 13. Heap: [8, 9]
- Pop 8, 9. Sum = 17. Total = 30. Result: 30
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.