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

Minimum Cost to Join Ropes

heaps · greedy · min-heap

You have ropes, a list of rope lengths. Joining two ropes of lengths a and b costs a + b and produces one rope of length a + b. Keep joining until a single rope remains and return the minimum total cost. If there is at most one rope, the cost is 0.

Examples

Input:  ropes = [4, 3, 2, 6]
Output: 29
Explanation: join 2 + 3 = 5 (cost 5), then 4 + 5 = 9 (cost 9), then 6 + 9 = 15 (cost 15).
             Total 5 + 9 + 15 = 29. Any other order costs more.

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…