Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Connect n ropes with minimum cost

Moderate
0/80
Average time to solve is 30m
24 upvotes
Asked in companies
OYOAmazonGoldman Sachs

Problem statement

There are given n ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. We need to connect the ropes with minimum cost.

Sample Input 1:
    4
    4 3 2 6        
Sample Output 1:
   29
Detailed explanation ( Input/output format, Notes, Images )
Input format :
Line 1: Size and  elements of array (separated by space) 
Output Format :
minimum cost of connecting ropes

Explanation

1) First, connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6, and 5.

2) Now connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9.

3) Finally, connect the two ropes, and all ropes are connected.

The total cost for connecting all ropes 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 strings of 3, 2 and 10), then connect 10 and 3 (we get two strings of 13 and 2). Finally, we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.

Video Solution
Unlock at level 3
(75% EXP penalty)
Connect n ropes with minimum cost
All tags
Sort by
Search icon

Interview problems

Easy Solution

import java.util.Scanner;

 

import java.util.PriorityQueue;

 

public class solution {

    static int minCost(int arr[], int n) {

        /*

         * Your class should be named Solution.Don't write main().Don't take

         * input, it is passed as function argument.Don't print output.Taking

         * input and printing output is handled automatically.

 

         */

                if(n==1)

                return arr[0];

 

            PriorityQueue<Integer> pq=new PriorityQueue<>();

            for(int i=0;i<n;i++)

            {

                pq.add(arr[i]);

            }

            

            int ans=0;

 

            while(!pq.isEmpty() && pq.size()>1)

            {

                int a=pq.poll();

                int b=pq.poll();

                ans+=a+b;

                pq.add(a+b);

            }

 

            return ans;

    }

}

60 views
0 replies
1 upvote

Interview problems

MinHeap Solution using C++ (Better than 94.48%)

#include <bits/stdc++.h>

 

int minCost(int arr[], int n)

{   priority_queue<int, vector<int>, greater<int>> minHeap;

    for(int i = 0; i<n; i++){

        minHeap.push(arr[i]);

    }

    int cost = 0;

    while(!minHeap.empty() && minHeap.size() > 1){

        int rope1 = minHeap.top();

        minHeap.pop();

        int rope2 = minHeap.top();

        minHeap.pop();

        cost += rope1+rope2;

        minHeap.push(rope1+rope2);

    }

    return cost;

}

 

314 views
0 replies
0 upvotes

Interview problems

Java solution using priority queue

    static int minCost(int arr[], int n) {

 

        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

 

        for(int i=0 ; i<n ; i++){

            minHeap.add(arr[i]);

        }

 

        int ans = 0;

        while(minHeap.size() > 1){

            int a = minHeap.remove();

            int b = minHeap.remove();

            int temp = a+b;

            ans += temp;

            minHeap.add(temp);

        }

 

        return ans;

 

    }

136 views
0 replies
0 upvotes

Interview problems

Java Solution Using Priority Queue

Step 1. Add all rope lengths into Priority Queue (Min Heap)

 

Step 2 : Take two min rope lengths, join them and add it to your total cost and add the joined rope length into the min Heap // Java Code   

PriorityQueue<Integer> pq = new PriorityQueue<>();

 

         int cost = 0;

 

        for(int i=0;i<n;i++){

            pq.add(arr[i]);

        }

 

        while(!pq.isEmpty()){

            int count = 0;

            int len = 0;

            while(count < 2){

                int value = pq.poll();

                len += value;

                cost += value;

                count++;

            }

 

            if(pq.isEmpty()) break;

            pq.add(len);

 

        }

 

        return cost;  

95 views
0 replies
0 upvotes

Interview problems

Easy & Best C++ Solution

int minCost(int arr[], int n)
{
	/*Write your code here. 
	 *Don't write main().
	 *Don't take input, it is passed as function argument.
	 *Don't print output.
	 *Taking input and printing output is handled automatically.
	*/
	priority_queue<int, vector<int>, greater<int>> pq;
        for(int i = 0; i < n; i++)
            pq.push(arr[i]);
        int cost = 0;
        while(pq.size() > 1)
        {
            int a = pq.top();
            pq.pop();
            int b = pq.top();
            pq.pop();
            int sum = a + b;
            cost += sum;
            pq.push(sum);
        }
        return cost;
}
492 views
0 replies
1 upvote

Interview problems

Connect n ropes with minimum cost

int minCost(int arr[], int n)

{

    int ans=0;

    priority_queue<int,vector<int>,greater<int>> pq;

    for(int i=0;i<n;i++){

        pq.push(arr[i]);

    }

    while(pq.size()>1){

        int x=pq.top();

        pq.pop();

        int y=pq.top();

        pq.pop();

        ans+=(x+y);

        pq.push(x+y);

    }

    return ans;

}

 

124 views
0 replies
0 upvotes

Interview problems

99% execution time in java using priority queue

static int minCost(int arr[], int n) {

        PriorityQueue<Integer> pq=new PriorityQueue<>();

        for(int i:arr)

        {

            pq.offer(i);

        }

        int cost=0;

        while(pq.size()>1)

        {

            int a=pq.poll();

            a+=pq.poll();

            cost+=a;

            pq.offer(a);

        }

        return cost;

 

    }

99 views
0 replies
0 upvotes

Interview problems

c++ easiest

#include<bits/stdc++.h>
int minCost(int arr[], int n)
{ 
	if(n==1)return arr[0];
	priority_queue<int,vector<int>,greater<int>>pq;
	for(int i=0;i<n;i++)
	{
		pq.push(arr[i]);
	}
	int cost=0;
	while(pq.size()>1)
	{
		int first=pq.top();
pq.pop();
       int second=pq.top();
pq.pop();
	   int sum=first+second;
	   cost+=sum;
	   pq.push(sum);
	}
	return cost;
}
192 views
0 replies
0 upvotes

Interview problems

Using minHeap (priorityQueue)

int minCost(int arr[], int n){

    priority_queue<int, vector<int>, greater<int>> pq;

 

    for(int i=0; i<n; i++){

        pq.push(arr[i]);

    }

    int res = 0;

    while(pq.size() != 1){

        int n1 = pq.top();

        pq.pop();

        int n2 = pq.top();

        pq.pop();

 

        int sum = n1+n2;

        res += sum;

        pq.push(sum);

    }

    return res;

}

datastructures

104 views
0 replies
0 upvotes

Interview problems

Connect n ropes with minimum cost Using C++

//Tejash maurya

priority_queue<int, vector<int>, greater<int> > pq; //creation of min heap

        

        for(int i=0;i<n;i++)

        {

            pq.push(arr[i]);

        }

        

        int cost = 0;

        while(pq.size() > 1)

        {

            int a = pq.top();

            pq.pop();

            

            int b = pq.top();

            pq.pop();

            

            int ans = a + b;

            

            cost = ans + cost;

            pq.push(ans);

        }

        return cost;

}

 

180 views
0 replies
2 upvotes
Full screen
Console