I am trying to solve a problem on Hacker Rank and the question is as follows:
Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value \$K\$. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with:
sweetness =(1× Least sweet cookie + 2× 2nd least sweet cookie).He repeats this procedure until all the cookies in his collection have a sweetness \$\ge K\$. You are given Jesse's cookies. Print the number of operations required to give the cookies a sweetness \$\ge K\$. Print \$−1\$ if this isn't possible.
Input Format
The first line consists of integers \$N\$, the number of cookies and \$K\$, the minimum required sweetness, separated by a space. The next line contains \$N\$ integers describing the array \$A\$ where \$Ai\$ is the sweetness of the \$i\$th cookie in Jesse's collection.
Constraints
\$1\le N\le 10^6\$
\$0\le K\le 10^9\$
\$0\le Ai\le 10^6\$Output Format
Output the number of operations that are needed to increase the cookie's sweetness \$\ge k\$. Output \$−1\$ if this isn't possible.
For this I have written code in Java like this:
public class Solution {
public int getMinStepsToGetK(long k,LinkedList<Integer> newList){
Collections.sort(newList);
int count=0;
while(newList.getFirst()<k){
if(newList.size()>=2){
count++;
int tempFirst = newList.removeFirst();
int tempSecond = newList.removeFirst();
newList.add(tempFirst+(tempSecond*2));
Collections.sort(newList);
}
else{
return -1;
}
}
return count;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Solution newObj = new Solution();
Scanner scanObj = new Scanner(System.in);
int numOfCookies = scanObj.nextInt();
long minSweetness = scanObj.nextLong();
LinkedList<Integer> newList = new LinkedList<Integer>();
for(int i=0;i<numOfCookies;i++){
newList.add(scanObj.nextInt());
}
System.out.println(newObj.getMinStepsToGetK(minSweetness,newList));
}
}
For the above code I am getting half of my test cases right and the other half is giving time out exception (taking more than 4 seconds to give output). My question is basically: where can I improve the performance of the code? Is there any other approach which I should go about?