All problems
1080MediumArrayGreedyHeap (Priority Queue)

Joining Every Rod Into One

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1167Minimum Cost to Connect Sticks

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def connect_sticks(rods: list[int]) -> int:
Java
public int connectSticks(int[] rods)
September 7
Apply