Skip to content
BytePatterns

Cheapest Rope Joining

MediumGreedy#greedy#min-heap~25m

Problem

A rigger has several ropes with known lengths and must splice them into one. Splicing two ropes costs the sum of their lengths and produces a rope of that combined length, which can be spliced again later. Return the smallest total cost of ending up with a single rope. With one rope or none there is nothing to splice.

Examples

Input:  lengths = [4, 3, 2, 6]
Output: 29
Why:    2 + 3 = 5, then 4 + 5 = 9, then 6 + 9 = 15, and 5 + 9 + 15 = 29
Input:  lengths = [1, 1, 1, 1]
Output: 8
Why:    two pairs cost 2 each, then the two halves cost 4
Input:  lengths = [8]
Output: 0
Why:    edge case, already a single rope

Hints

0 / 3

Stuck on the idea rather than the code? Huffman Intuition covers it.