Open In App

Connect n ropes with minimum cost

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of rope lengths, connect all ropes into a single rope with the minimum total cost. The cost to connect two ropes is the sum of their lengths.

Examples:

Input: arr[] = [4, 3, 2, 6]
Output: 29
Explanation: We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation 9 + 6 =15. Total cost is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes.

Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3 (we get two rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.

Connect-n-ropes-with-minimum-cost

Input: arr[] = [10]
Output: 0
Explanation: Since there is only one rope, no connections are needed, so the cost is 0.

[Naive Approach] Greedy with Repeated Sorting - O(n^2*log(n)) Time and O(n) Space

The approach used in this solution is a greedy algorithm. The idea is to always connect the two smallest ropes first, as this minimizes the cost at each step. To achieve this, the array of rope lengths is sorted, and the two smallest ropes are chosen for connection. Their combined length is then added back into the array, and the process repeats until only one rope remains.

By sorting the ropes at each step, we ensure that the smallest ropes are always picked, minimizing the total connection cost. The algorithm continues until all ropes are merged into one, and the total cost is accumulated. This method ensures that the problem is solved with a minimal total cost.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to return the minimum cost of connecting the ropes.
int minCost(vector<int>& arr) {
    int totalCost = 0;
    while (arr.size() > 1) {
        sort(arr.begin(), arr.end());
        int first = arr[0];
        int second = arr[1];
        arr.erase(arr.begin());
        arr.erase(arr.begin());
        int cost = first + second;
        totalCost += cost;
        arr.push_back(cost);
    }
    return totalCost;
}

int main() {
    vector<int> ropes = {4, 3, 2, 6};
    cout << minCost(ropes) << endl;
    return 0;
}
Java
// Function to return the minimum cost of connecting the ropes.
import java.util.*;

public class GfG {
    public static int minCost(int[] arr) {
        int totalCost = 0;
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for (int rope : arr) {
            minHeap.add(rope);
        }
        while (minHeap.size() > 1) {
            int first = minHeap.poll();
            int second = minHeap.poll();
            int cost = first + second;
            totalCost += cost;
            minHeap.add(cost);
        }
        return totalCost;
    }

    public static void main(String[] args) {
        int[] ropes = {4, 3, 2, 6};
        System.out.println(minCost(ropes));
    }
}
Python
# Function to return the minimum cost of connecting the ropes.
def minCost(arr):
    totalCost = 0
    while len(arr) > 1:
        arr.sort()
        first = arr.pop(0)
        second = arr.pop(0)
        cost = first + second
        totalCost += cost
        arr.append(cost)
    return totalCost

if __name__ == '__main__':
    ropes = [4, 3, 2, 6]
    print(minCost(ropes))
C#
// Function to return the minimum cost of connecting the ropes.
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {
    static int MinCost(List<int> arr) {
        int totalCost = 0;
        while (arr.Count > 1) {
            arr.Sort();
            int first = arr[0];
            int second = arr[1];
            arr.RemoveAt(0);
            arr.RemoveAt(0);
            int cost = first + second;
            totalCost += cost;
            arr.Add(cost);
        }
        return totalCost;
    }

    static void Main() {
        List<int> ropes = new List<int> {4, 3, 2, 6};
        Console.WriteLine(MinCost(ropes));
    }
}
JavaScript
// Function to return the minimum cost of connecting the ropes.
function minCost(arr) {
    let totalCost = 0;
    while (arr.length > 1) {
        arr.sort((a, b) => a - b);
        const first = arr[0];
        const second = arr[1];
        arr.splice(0, 2);
        const cost = first + second;
        totalCost += cost;
        arr.push(cost);
    }
    return totalCost;
}

const ropes = [4, 3, 2, 6];
console.log(minCost(ropes));

Output
29

[Expected Approach] Greedy with Heap - O(n*log(n)) Time and O(n) Space

The idea is to connect the smallest two ropes first, as the lengths of the ropes that are picked early are included more than once in the total cost. This approach is similar to the concept used in Huffman Coding, where the smaller elements are combined earlier, which results in a smaller cost for subsequent operations.

To implement the idea, use a min-heap (priority queue) and push all elements into it. While the heap contains more than one element, repeatedly extract the two smallest values, add them, and insert the sum back into the heap. Maintain a variable to track the total cost, incrementing it by the sum of the extracted values at each step. Once the process is complete, return the total cost.

C++
// C++ program for connecting n rope
// with minimum cost using min-heap
#include <bits/stdc++.h>
using namespace std;

int minCost(vector<int> &arr) {

    // Create a priority queue
    // By default 'less' is used which is for decreasing
    // order and 'greater' is used for increasing order
    priority_queue<int, vector<int>,
               greater<int>> pq(arr.begin(), arr.end());

    // Initialize result
    int res = 0;

    // While size of priority queue is more than 1
    while (pq.size() > 1) {

        // Extract shortest two ropes from pq
        int first = pq.top();
        pq.pop();
        int second = pq.top();
        pq.pop();

        // Connect the ropes: update result and
        // insert the new rope to pq
        res += first + second;
        pq.push(first + second);
    }

    return res;
}

int main() {

    vector<int> arr = {4, 3, 2, 6};
    cout << minCost(arr);
    return 0;
}
Java
// Java program for connecting n ropes
// with minimum cost using min-heap
import java.util.PriorityQueue;

class GfG {
  
     public static int minCost(int[] arr) {
      
        // Create a priority queue
        // By default, the priority queue is in
        // increasing order
        PriorityQueue<Integer> pq = new PriorityQueue<>();
       
        for (int num : arr) {
            pq.add(num);
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.size() > 1) {
          
            // Extract shortest two ropes from pq
            int first = pq.poll();
            int second = pq.poll();

            // Connect the ropes: update result and
            // insert the new rope to pq
            res += first + second;
            pq.add(first + second);
        }

        return res;
    }

    public static void main(String[] args) {
      
        int[] arr = {4, 3, 2, 6};
        System.out.println(minCost(arr));
    }
}
Python
# Python program for connecting n ropes
# with minimum cost using min-heap
import heapq

def minCost(arr):
  
    # Create a priority queue
    # By default, heapq provides a min-heap
    heapq.heapify(arr)

    # Initialize result
    res = 0

    # While size of priority queue is more than 1
    while len(arr) > 1:
      
        # Extract shortest two ropes from pq
        first = heapq.heappop(arr)
        second = heapq.heappop(arr)

        # Connect the ropes: update result and
        # insert the new rope to pq
        res += first + second
        heapq.heappush(arr, first + second)

    return res

if __name__ == "__main__":
  
    arr = [4, 3, 2, 6]
    print(minCost(arr))
C#
// C# program for connecting n ropes
// with minimum cost using min-heap
using System;
using System.Collections.Generic;

class GfG {
  
    static int minCost(int[] arr) {
      
        // Create a priority queue
        SortedSet<(int Value, int Index)> pq = 
                      new SortedSet<(int, int)>();
      
        for (int i = 0; i < arr.Length; i++) {
            pq.Add((arr[i], i));
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.Count > 1) {
          
            // Extract shortest two ropes from pq
            int first = pq.Min.Value;
            pq.Remove(pq.Min);

            int second = pq.Min.Value;
            pq.Remove(pq.Min);

            // Connect the ropes: update result and
            // insert the new rope to pq
            res += first + second;
            pq.Add((first + second, pq.Count + 1));
        }

        return res;
    }

    static void Main(string[] args) {
      
        int[] arr = { 4, 3, 2, 6 };
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// JavaScript program for connecting n ropes
// with minimum cost using min-heap

function minCost(arr) {
    // Create a min-heap and add all elements
    const pq = new MinHeap();
    arr.forEach(num => pq.push(num));

    // Initialize result
    let res = 0;

    // While size of priority queue is more than 1
    while (pq.size() > 1) {

        // Extract shortest two ropes from pq
        const first = pq.pop();
        const second = pq.pop();

        // Connect the ropes: update result and
        // insert the new rope to pq
        res += first + second;
        pq.push(first + second);
    }

    return res;
}

class MinHeap {
    constructor() {
        this.heap = [];
    }

    // Insert a value into the heap
    push(val) {
        this.heap.push(val);
        this.heapifyUp();
    }

    // Remove and return the smallest element
    pop() {
        if (this.heap.length === 1) {
            return this.heap.pop();
        }
        const root = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.heapifyDown();
        return root;
    }

    // Return the smallest element without removing it
    top() {
        return this.heap[0];
    }

    // Return the size of the heap
    size() {
        return this.heap.length;
    }

    // Restore the heap property upwards
    heapifyUp() {
        let index = this.heap.length - 1;
        while (index > 0) {
            const parentIndex = Math.floor(
                (index - 1) / 2
            );
            if (
                this.heap[index] >=
                this.heap[parentIndex]
            ) {
                break;
            }
            [
                this.heap[index],
                this.heap[parentIndex]
            ] = [
                this.heap[parentIndex],
                this.heap[index]
            ];
            index = parentIndex;
        }
    }

    // Restore the heap property downwards
    heapifyDown() {
        let index = 0;
        const size = this.heap.length;
        while (true) {
            const leftChild = 2 * index + 1;
            const rightChild = 2 * index + 2;
            let smallest = index;

            if (
                leftChild < size &&
                this.heap[leftChild] <
                this.heap[smallest]
            ) {
                smallest = leftChild;
            }

            if (
                rightChild < size &&
                this.heap[rightChild] <
                this.heap[smallest]
            ) {
                smallest = rightChild;
            }

            if (smallest === index) {
                break;
            }

            [
                this.heap[index],
                this.heap[smallest]
            ] = [
                this.heap[smallest],
                this.heap[index]
            ];
            index = smallest;
        }
    }
}

const arr = [4, 3, 2, 6];
console.log(minCost(arr));

Output
29

Article Tags :
Practice Tags :

Similar Reads