• + 0 comments

    Java 15 solutions (1 TLE tho in Java 8, haven't figured out why yet..)

       public static int cookies(int k, List<Integer> A) {
            List<Integer> inputs = A;
            inputs.sort(Comparator.reverseOrder());
            Stack<Integer> stack = new Stack<>();
            for (Integer i : inputs) {
                stack.push(i);
            }
    
            Queue<Integer> temp = new LinkedList<>();
            int count = 0;
            while(!stack.isEmpty() || !temp.isEmpty()) {
                // check condition
                int minStack = stack.isEmpty() ? Integer.MAX_VALUE : stack.peek();
                int minTemp = temp.isEmpty() ? Integer.MAX_VALUE : temp.peek();
                if (Math.min(minStack, minTemp) >= k) {
                    return count;
                }
                
                Optional<Integer> maybeSmall = getAndPopSmallest(stack, temp);
                Optional<Integer> maybeBig = getAndPopSmallest(stack, temp);
                if (maybeBig.isPresent()) {
                    temp.add(maybeSmall.get() + 2 * maybeBig.get());
                } else {
                    break;
                }
                count++;
            }
            return -1;
        }
    
        private static Optional<Integer> getAndPopSmallest(Stack<Integer> stack, Queue<Integer> temp) {
            if (stack.isEmpty() && temp.isEmpty()) {
                return Optional.empty();
            } else if (stack.isEmpty()) {
                return Optional.of(temp.poll());
            } else if (temp.isEmpty()) {
                return Optional.of(stack.pop());
            } else if (stack.peek() <= temp.peek()) {
                return Optional.of(stack.pop());
            } else {
                return Optional.of(temp.poll());
            }
        }