We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Heap
  4. Jesse and Cookies
  5. Discussions

Jesse and Cookies

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • Gouzi
    4 months ago+ 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());
            }
        }
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy