Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
1,654 views

in Online Assessments by Expert (108,280 points) | 1,654 views

1 Answer

0 like 0 dislike
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        int arr[] = { 4, 6, 8 };
        System.out.println(solve(arr));
    }
    
    private static int solve(int[] arr){
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        
        for(int a : arr)
            pq.add(a);
        int cost = 0;
        while(pq.size() >= 2){
            int x = pq.remove();
            int y = pq.remove();
            cost += x+y;
            pq.add(x+y);
        }
        
        return cost;
    }
}
by (150 points)