joshita / dev

Published

- 1 min read

Minimum cost to connect ropes

img of Minimum cost to connect ropes

Given are N ropes of different lengths, the task is to connect these ropes into one rope with minimum cost, such that the cost to connect two ropes is equal to the sum of their lengths.

   
private int minimumCostToConnectRopes(int [] arr) {

    if(arr.length == 0) {
        return 0;
    }
    int cost = 0;
    PriorityQueue<Integer> pq = new PriorityQueue();
    for (int i=0; i < arr.length; i++) {
        pq.add(arr[i]);
    }
    
    while(!pq.isEmpty) {
        int currentCost = pq.poll() + pq.poll();
        cost += currentCost;

        pq.add(currentCost);
    }

    return cost;

}