Jesse and Cookies

  • + 0 comments

    My Java solution using a Priority Queue or min heap

    public static int cookies(int k, List<Integer> A) {
        // Write your code here
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        int operations=0;
        for(int a: A)
        {
          if(a<k)
          {
            pq.add(a);
          }
          
        }
        if(pq.isEmpty())
        {
          return 0;
        }
        while(!pq.isEmpty())
        {
          int a = pq.remove();
          if(!pq.isEmpty())
          {
            int b=pq.remove();
            int res = a+2*b;
            if(res<k)
            {
              pq.add(res);
            }
          }
          operations++;
        }
        return operations==A.size() ? -1 : operations;
      }