We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java Solution using Priority Queue -> public class Solution {
// Complete the getMinimumCost function below.
static int getMinimumCost(int k, int[] c) {
Arrays.sort(c);
PriorityQueue<Pair> q = new PriorityQueue<>((a,b)->
{
return a.cnt-b.cnt;
});
int s = 0;
if(c.length<k)
{
for(int i =0;i<c.length;i++)
{
s=s+c[i];
}
return s;
}
int l = c.length-1;
for(int i =0;i<k;i++)
{
q.offer(new Pair(1,i));
s = s+c[l];
l--;
}
while(l>=0)
{
Pair temp = q.poll();
System.out.println("cnt here is"+temp.cnt);
int v = (temp.cnt+1)*c[l];
s=s+v;
q.offer(new Pair(temp.cnt+1,temp.val));
l--;
}
return s;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nk = scanner.nextLine().split(" ");
int n = Integer.parseInt(nk[0]);
int k = Integer.parseInt(nk[1]);
int[] c = new int[n];
String[] cItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int cItem = Integer.parseInt(cItems[i]);
c[i] = cItem;
}
int minimumCost = getMinimumCost(k, c);
bufferedWriter.write(String.valueOf(minimumCost));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Greedy Florist
You are viewing a single comment's thread. Return to all comments →
Java Solution using Priority Queue -> public class Solution {
}