Pattern visualizer
Minimum Cost to Connect Sticks
Every stick's length gets added to the running cost once for every merge it takes part in AFTER it is created. A stick combined early sits inside the pile through more later merges, so it must be a SHORT one — the two shortest sticks available should always be connected next. A min-heap keeps the two shortest on top with no scanning: pop twice, connect, push the sum back in, repeat. Animated on: Sticks = [2, 4, 3]. Repeatedly connect any two sticks for a cost equal to their summed length, until one stick remains. Return the minimum total cost..
Always merge the two shortest sticks first
Push the first stick, 4. One node, so it is trivially the root.
1FUNCTION minCostConnectSticks(sticks):2 heap <- BUILD MIN-HEAP FROM sticks3 cost <- 04 WHILE LENGTH(heap) > 15 a <- EXTRACT-MIN(heap)6 b <- EXTRACT-MIN(heap)7 cost <- cost + a + b8 INSERT (a + b) INTO heap9 RETURN cost
← / → step · space play · Home restart