Connect n ropes with minimum cost Java Code Solution
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Test{
public static void main(String[] args) {
//Taking input using class Scanner
Scanner in = new Scanner(System.in);
//Taking count of testcases
int t = in.nextInt();
while (t-- > 0) {
//takling count of elements
int n = in.nextInt();
//Creating an array of size n
long arr[] = new long[n];
//inserting elements to the array
for (int i = 0; i < n; ++i) arr[i] = in.nextLong();
//calling minCost method of class solve
System.out.println(new Solution().minCost(arr, n));
}
}
}
// } Driver Code Ends
class Solution{
long minCost(long arr[], int n) {
PriorityQueue<Long> heap = new PriorityQueue<>();
for(int i=0;i<n;i++){
heap.add(arr[i]);
}
long cost = 0;
while(heap.size()>=2){
long length = heap.poll() + heap.poll();
cost = cost + length;
heap.add(length);
}
return cost;
}
}
Comments
Post a Comment