text: Maximum number of diamonds that can be gained in K minutes | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxDiamonds ( int A [ ] , int N , int K ) { priority_queue < int > pq ; for ( int i = 0 ; i < N ; i ++ ) { pq . push ( A [ i ] ) ; } int ans = 0 ; while ( ! pq . empty ( ) && K -- ) { int top = pq . top ( ) ; pq . pop ( ) ; ans += top ; top = top / 2 ; pq . push ( top ) ; } cout << ans ; } int main ( ) { int A [ ] = { 2 , 1 , 7 , 4 , 2 } ; int K = 3 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maxDiamonds ( A , N , K ) ; return 0 ; }