text: Maximum number of diamonds that can be gained in K minutes | Java program for the above approach ; Function to find the maximum number of diamonds that can be gained in exactly K minutes ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the pq ; Pop it from the pq ; Add it to the answer ; Divide it by 2 and push it back to the pq ; Print the answer ; Driver Code
code: import java . util . * ; class GFG { static void maxDiamonds ( int A [ ] , int N , int K ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( ( a , b ) -> b - a ) ; for ( int i = 0 ; i < N ; i ++ ) { pq . add ( A [ i ] ) ; } int ans = 0 ; while ( ! pq . isEmpty ( ) && K -- > 0 ) { int top = pq . peek ( ) ; pq . remove ( ) ; ans += top ; top = top / 2 ; pq . add ( top ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 1 , 7 , 4 , 2 } ; int K = 3 ; int N = A . length ; maxDiamonds ( A , N , K ) ; } }