Minimum Cost to Connect Sticks
Real-world version: Joining Every Rod Into OneThe statement here is our own: the same inputs, outputs and technique.
A pile of rods has the lengths rods. Joining two rods costs their two lengths added together and leaves a single rod of that length in their place.
Join rods until only one remains. Return the smallest total cost.
Examples
Example 1
- Input
- rods = [1, 2, 3, 4]
- Output
- 19
Joining 1 and 2 costs three, joining that with 3 costs six, and joining that with 4 costs ten, nineteen in all. Any other order charges the short rods more times over.
Example 2
- Input
- rods = [1, 1]
- Output
- 2
One join of the two rods, charging their two lengths.
Example 3
- Input
- rods = [1, 2, 4, 8, 16]
- Output
- 56
Each join takes the two shortest rods left, so the four joins cost three, seven, fifteen and thirty-one.
Constraints
- 1 <= rods.length <= 10^4
- 1 <= rods[i] <= 10^4
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def connect_sticks(rods: list[int]) -> int:public int connectSticks(int[] rods)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Make Array Zero by Subtracting Equal AmountsReal-world version: Rounds Needed to Clear Every ReadingEasy
- Meeting Rooms IIReal-world version: Peak Charging Bay DemandMedium
- Task SchedulerReal-world version: Press Die CooldownMedium
- Maximum Number of Events That Can Be AttendedReal-world version: Most Inspections BookedMedium