Question:
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. The task is to connect the ropes with minimum cost. Given N size array arr[] contains the lengths of the ropes.
Example 1:
Input: n = 4 arr[] = {4, 3, 2, 6} Output: 29 Explanation: We can connect the ropes in following ways.
- First connect ropes of lengths 2 and 3. Which makes the array {4, 5, 6}. Cost of this operation 2+3 = 5.
- Now connect ropes of lengths 4 and 5. Which makes the array {9, 6}. Cost of this operation 4+5 = 9.
- Finally connect the two ropes and all ropes have connected. Cost of this operation 9+6 =15 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 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.
28 = 62. Your Task: You don't need to read input or print anything. Your task isto complete the function minCost() which takes an integer array arr[] and an integer n as arguments and returns the minimum cost.
Expected Time Complexity : O(nlogn) Expected Auxilliary Space : O(n)
Constraints: 1 ≤ N ≤ 200000 1 ≤ arr[i] ≤ 106
It is one of the questions from GeeksforGeeks, Minimum Cost of ropes.
class Solution:
#Function to return the minimum cost of connecting the ropes.
def minCost(self,arr,n) :
# code here
arr.sort()
arr2=[]
cost=0
for x in range(len(arr)-1):
cost=arr[0]+arr[1]
arr.remove(arr[0])
arr.remove(arr[0])
arr.append(cost)
arr2.append(cost)
arr.sort()
return(sum(arr2))
The code took 8 secs to run for one of the test cases
How can I reduce the time of the code?
Please suggest some measures to improve this code.