Jesse and Cookies HackerRank Solution

Jesse and Cookies HackerRank Solution
Jesse and Cookies HackerRank Solution

In this Jesse and Cookies HackerRank solution, Jesse loves cookies and wants the sweetness of some cookies to be greater than value . To do this, two cookies with the least sweetness are repeatedly mixed. This creates a special combined cookie with:

sweetness  Least sweet cookie   2nd least sweet cookie).

This occurs until all the cookies have a sweetness .

Given the sweetness of a number of cookies, determine the minimum number of operations required. If it is not possible, return .

Jesse and Cookies HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in C#

public static int cookies(int k, List<int> A)
    {
       
        if (A.Count < 1)
            return -1;
           
        int count = 0;
        PriorityQueue<int, int> q = new PriorityQueue<int, int>();
       
        for(int i =0; i < A.Count; i++)
        {
            q.Enqueue(A[i], A[i]);
        }
       
        while(q.Count > 1 && q.Peek() < k)
        {
            int min = q.Peek();
            int val = q.Dequeue()  + 2 * q.Dequeue() ;
            if (val < min)
              return -1;
            count++;
            q.Enqueue(val,val);
           
        }
       
        if (q.Peek() >= k)
            return count;
        else
            return -1;
       


    }

Problem Solution in C++

int cookies(int k, vector<int> A) {
    priority_queue<int, vector<int>, greater<int>> pq;
    int count=0;
    for(int i=0;i<A.size();i++)
        pq.push(A[i]);
    while(pq.top()<k)
    {
        if(pq.size()==1)
            return -1;
        count++;
        int t1=pq.top();
        pq.pop();
        int t2=pq.top();
        pq.pop();
        pq.push(t1+(2*t2));
    }  
    return count;
}