The problem involves connecting a set of sticks into one stick. The cost of connecting two sticks is equal to the sum of their lengths. The goal is to minimize the total cost of connecting all the sticks.
To solve this efficiently, we use a min-heap to always connect the two smallest sticks first, minimizing the cost at each step.
class Solution {
public int connectSticks(int[] sticks) {
// Step 1: Add all sticks to a min-heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int stick : sticks) {
minHeap.offer(stick);
}
int totalCost = 0;
// Step 2: Combine sticks until only one stick remains
while (minHeap.size() > 1) {
int stick1 = minHeap.poll(); // Smallest stick
int stick2 = minHeap.poll(); // Second smallest stick
int cost = stick1 + stick2; // Cost to combine them
totalCost += cost;
minHeap.offer(cost); // Add the combined stick back to the heap
}
return totalCost;
}
}
O(n log n)
โ Adding all sticks to the heap.O(n log n)
โ Combining sticks involves n-1
heap operations.O(n log n)
.Input: sticks = [2, 4, 3]
Output: 14
Explanation:
- Combine sticks 2 and 3 for a cost of 5. Sticks = [5, 4].
- Combine sticks 5 and 4 for a cost of 9. Sticks = [9].
- Total cost = 5 + 9 = 14.