text: Maximum number of diamonds that can be gained in K minutes | 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: function maxDiamonds ( A , N , K ) { let pq = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { pq . push ( A [ i ] ) ; } let ans = 0 ; pq . sort ( ( a , b ) => a - b ) while ( pq . length && K -- ) { pq . sort ( ( a , b ) => a - b ) let top = pq [ pq . length - 1 ] ; pq . pop ( ) ; ans += top ; top = Math . floor ( top / 2 ) ; pq . push ( top ) ; } document . write ( ans ) ; } let A = [ 2 , 1 , 7 , 4 , 2 ] ; let K = 3 ; let N = A . length ; maxDiamonds ( A , N , K ) ;