Jesse and Cookies

  • + 0 comments

    C# code

    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;
            
    
        }