Problem 497181 · easy · Level 04 Non-Linear Data Structures

Welding Pipe Sections Into One

heaps · greedy · min-heap

A plumber has pipe sections whose lengths are listed in ropes. Welding two sections of lengths a and b together takes a + b minutes and leaves one section of length a + b. She keeps welding pairs until a single section is left. Return the fewest total minutes the whole job can take. With at most one section there is nothing to weld, so the answer is 0.

Examples

Input:  ropes = [5, 2, 8, 3]
Output: 33
Explanation: join 2 + 3 = 5 (cost 5), then 5 + 5 = 10 (cost 10), then 8 + 10 = 18 (cost 18).
             Total 5 + 10 + 18 = 33. Any other order costs at least as much.

Input:  ropes = [8]
Output: 0

Constraints

  • 0 <= len(ropes) <= 10**5, 1 <= ropes[i] <= 10**4
  • Target complexity: O(n log n).

Goals

  • Recognise that always combining the two shortest pieces minimises the total
  • Maintain the working set of rope lengths in a min-heap
  • Accumulate the cost of every join
Starting Python…