Minimum Cost to Connect Sticks
Join all the sticks into one at the lowest cost by always joining the two shortest first.
Given an array sticks
Example 1
Output: 14
Explanation: join 2 + 3 = 5 (cost 5), then 5 + 4 = 9 (cost 9), so 5 + 9 = 14.
Example 2
Output: 30
Explanation: join 1 + 3 = 4, then 4 + 5 = 9, then 9 + 8 = 17, so 4 + 9 + 17 = 30.
The Idea
Picture someone who glues sticks end to end for you and charges by the length of every new stick they make. Glue a 1 to a 3 and you pay 4. Glue that 4 to a 5 and you pay 9. You want one long stick in the end, and you want to pay as little as possible.
The final stick always has the same length: in Example 2 it is 1 + 8 + 3 + 5 = 17. So does the order of the joins matter at all? Try the long sticks first: 8 + 5 = 13 costs 13, then 13 + 3 = 16 costs 16, then 16 + 1 = 17 costs 17. That adds up to 46, far more than the 30 of Example 2.
Where does the difference come from? Look at the picture below, which draws the joins of Example 2 from the bottom up.
The orange box, stick 1, and the teal boxes, 3, 5 and 8, are the sticks we start with, and each blue box is a new stick made by a join. Follow the orange line up from stick 1: it goes into 4, then into 9, then into 17. The length 1 is part of all three new sticks, so it is paid three times. Stick 8 goes into the third join only, so it is paid once.
So the total cost is each starting stick's length times the number of joins it goes through: 1 × 3 + 3 × 3 + 5 × 2 + 8 × 1 = 30. A stick joined early goes through more joins than one joined late. That is the key insight: short sticks should be joined early and long sticks late.
It leads to a simple rule. At every step, join the two shortest sticks there are right now, counting the new sticks made by earlier joins. Picking each join by what is cheapest at that moment, without planning further ahead, is called a greedy choice. In Example 2 the rule joins 1 + 3 first, then 4 + 5, where the 4 is the stick just made, then 9 + 8: the order in the picture.
Solution Approach
Turning the rule into code means settling three things: why trying every order of joins is too slow, why joining the two shortest sticks never loses, and how to find the two shortest sticks again after each join.
Trying every order
Why not try every order of joins and keep the cheapest? With four sticks there are 6 pairs to choose for the first join, then 3, then 1, so 18 orders. With ten sticks there are about 2.6 billion orders, and each extra stick multiplies that number again.
Why the two shortest sticks are safe
How do we know the greedy choice never costs more than some cleverer order? Draw any order of joins like the picture. At the bottom there is a join of two starting sticks that go through more joins than any other stick; in the picture these are 1 and 3, with three joins each.
If the two shortest sticks are not in that bottom join, swap them in. A shorter length moves to a place where it is paid more often, and a longer length to a place where it is paid less often, so the total cannot go up. So some cheapest order starts by joining the two shortest sticks. After that join, the new stick is simply one more stick, and the same reasoning picks the next join.
Finding the two shortest sticks each time
Where are the two shortest sticks after a join? Sorting the lengths once is not enough, because each new stick has to find its place among the others. In Example 2, after 1 + 3 = 4 the sticks are 5, 8 and the new 4, and the new 4 is the shortest. With n sticks, scanning all of them for the two shortest before every join takes about n² steps in total.
A min-heap does this faster. It is a structure that always hands out its smallest value first, and adding or removing a value takes about log n steps. Here the heap is a PriorityQueue<Integer>Integer::compare
PriorityQueue<Integer> heap = new PriorityQueue<>(Integer::compare);
Java Solution
The method connectSticks
- First, create the min-heap
withheap and add every length fromnew PriorityQueue<>(Integer::compare) to it.sticks - Set
to 0. It adds up what the joins cost.cost - While
holds more than one stick, take out the two shortest with two calls toheap and add them intoheap.poll() , the length of the new stick. Addjoined tojoined , then putcost back intojoined , since it may be one of the two shortest for a later join.heap - When one stick is left, return
. With a single stick the loop never runs, so the cost stays 0.cost
The main[2, 2, 3, 3]joinLeftToRight
import java.util.Arrays;
import java.util.PriorityQueue;
public class MinimumCostToConnectSticks {
public static int connectSticks(int[] sticks) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Integer::compare); // shortest on top
for (int s : sticks) {
heap.add(s);
}
int cost = 0;
while (heap.size() > 1) {
int joined = heap.poll() + heap.poll(); // join the two shortest
cost += joined; // pay the new stick's length
heap.add(joined); // the new stick goes back in
}
return cost;
}
// Sort once, then keep adding the next stick to one growing stick.
static int joinLeftToRight(int[] sticks) {
int[] sorted = sticks.clone();
Arrays.sort(sorted);
int cost = 0;
int current = sorted.length > 0 ? sorted[0] : 0;
for (int i = 1; i < sorted.length; i++) {
current += sorted[i];
cost += current;
}
return cost;
}
public static void main(String[] args) {
int[][] inputs = {{2, 4, 3}, {1, 8, 3, 5}, {5}, {2, 2, 3, 3}};
for (int[] sticks : inputs) {
System.out.println(Arrays.toString(sticks) + " -> " + connectSticks(sticks));
}
int[] trap = {2, 2, 3, 3};
System.out.println("left to right " + Arrays.toString(trap)
+ " -> " + joinLeftToRight(trap));
}
}
Running it prints:
[2, 4, 3] -> 14
[1, 8, 3, 5] -> 30
[5] -> 0
[2, 2, 3, 3] -> 20
left to right [2, 2, 3, 3] -> 21
The line [1, 8, 3, 5] -> 30[5] -> 0
Now compare the last two lines. On [2, 2, 3, 3]
Complexity
The work is filling the heap, then n - 1 joins, each with two removals and one insert.
- Time: O(n log n), because each of the n first inserts and each of the 3(n - 1) heap operations in the joins costs about log n steps, in a heap that never holds more than the n starting sticks.
- Space: O(n), because the heap starts with all n stick lengths and shrinks by one with each join.
A heap that always hands over the best next choice also drives