Skip to main content

Posts

Showing posts with the label Heap

Jesse and Cookies Hackerrank Solution Java | Data Structure

 Jesse and Cookies Hackerrank Solution Java | Data Structure Note: Due to TLE i modified the some part of code. Sample Input STDIN Function ----- -------- 6 7 A[] size n = 6, k = 7 1 2 3 9 10 12 A = [1, 2, 3, 9, 10, 12] Sample Output 2 import  java.io.*; import  java.math.*; import  java.text.*; import  java.util.*; import  java.util.regex.*; public   class  Solution {      static  PriorityQueue<Integer> heap =  new  PriorityQueue<>();      /*      * Complete the cookies function below.      */      static   int  cookies( int  k) {                   int  count =  0 ;          while (heap.peek()<k && heap.size()>= 2 ){             heap.add(heap.remove()+heap.remove()* 2 );             count++;         }          if (heap.size()== 1  && heap.peek()<k){             count = - 1 ;         }          return  count;     }      public   static   void  main(String[] args) {         Scanner scn =  new  Scann

QHEAP1 Hackerrank Solution Java | Data Structure

 QHEAP1 Hackerrank Solution Java | Data Structure For Explanation: Sample Input STDIN Function ----- -------- 5 Q = 5 1 4 insert 4 1 9 insert 9 3 print minimum 2 4 delete 4 3 print minimum Sample Output 4 9 Code: import  java.io.*; import  java.util.*; public   class  Solution {      public   static   void  main(String[] args) {          /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */         Scanner scn =  new  Scanner(System.in);         PriorityQueue<Integer> heap =  new  PriorityQueue<Integer>();          int  q = scn.nextInt();          while (q--> 0 ){              int  q1 = scn.nextInt();              if (q1== 1 ){                  int  num = scn.nextInt();                 heap.add(num);             } else   if (q1== 2 ){                  int  num = scn.nextInt();                 heap.remove(num);             } else   if (q1== 3 ){