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.
/* * Complete the 'cookies' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER k * 2. INTEGER_ARRAY A */publicstaticintcookies(intk,List<Integer>A){// Initialize variablesList<Integer>cookies=A;// List of cookiesintsweetness=k;// Desired sweetness levelfinalintnotPossible=-1;// Constant for indicating impossibility// Create a priority queue to store cookies with sweetness less than 'k'PriorityQueue<Integer>priorityQueue=newPriorityQueue<>();intnumberOfOperation=0;// Counter for operations// Add eligible cookies to the priority queuefor(Integercookie:cookies){if(cookie<sweetness){priorityQueue.add(cookie);}}// If no eligible cookies, return 0if(priorityQueue.isEmpty()){return0;}// Process cookies in pairswhile(!priorityQueue.isEmpty()){intcookie=priorityQueue.poll();// Get the least sweet cookieif(!priorityQueue.isEmpty()){intcookie2=priorityQueue.poll();// Get the second least sweet cookie// Calculate new sweetness after combining the two cookiesintnewSweetness=cookie+(2*cookie2);// If new sweetness is still less than 'k', add it back to the queueif(newSweetness<k){priorityQueue.add(newSweetness);}}numberOfOperation++;// Increment operation count}// If all cookies are used, return 'notPossible', otherwise return the operation countreturnnumberOfOperation==cookies.size()?notPossible:numberOfOperation;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Jesse and Cookies
You are viewing a single comment's thread. Return to all comments →
Java solution using Priority Queue.