Intermediate Level
Implement the minimumCostConnectRopes method that returns the minimum total cost needed to connect all ropes.
The input array ropes contains the lengths of size ropes.
Your task is to connect all ropes into one rope with the minimum total cost. Whenever two ropes are connected, the cost is equal to the sum of their lengths.
For example, for [4,3,2,6], the minimum total cost is 29 when the smallest ropes are connected first.
Always connect the two shortest ropes first.
This greedy choice keeps future connection costs as small as possible. Use a min heap to quickly get the two smallest rope lengths each time.
After connecting two ropes, add their sum to the total cost and push the combined rope back into the heap. Continue until only one rope remains.
Pseudocode:
function minimumCostConnectRopes(ropes, size):
create minHeap from ropes
totalCost = 0
while heap size > 1:
first = remove smallest from minHeap
second = remove smallest from minHeap
cost = first + second
totalCost = totalCost + cost
push cost into minHeap
return totalCost