Jesse and Cookies

  • + 0 comments

    Java 15 solution using PriorityQueue:

    public static int cookies(int k, List<Integer> cookies){
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(cookies);
        if(isAllCookiesSweeterThanK(k,pq))return 0;
    
        int counter = 0;
        while(!isAllCookiesSweeterThanK(k, pq)){
            if(pq.size()==1)return -1;
            pq.add(pq.poll() + pq.poll()*2);
            counter++;
        }
    
        return counter;
    }
    
    private static boolean isAllCookiesSweeterThanK(int k, PriorityQueue<Integer> pq){
        Optional<Integer> ans = pq.stream().filter(i -> i < k).findFirst();
        if(ans.isEmpty())return true;
        return false;
    }