Maximum amount of capital required for selecting at most K projects | C ++ program for the above approach ; Function to calculate maximum capital obtained after choosing at most K projects whose capital is less than the given cost of projects ; Stores all projects with capital at most W ; Stores the pair of { C [ i ] , i } ; Traverse the vector C [ ] ; Sort the vector v ; If capital is at most W ; Push the profit into priority queue ; Increment j by one ; If pq is not empty ; Update the capital W ; Delete the top of pq ; Decrement K by one ; Return the maximum capital ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizedCapital ( int K , int W , vector < int > & profits , vector < int > & capital ) { priority_queue < int > pq ; vector < pair < int , int > > v ; for ( int i = 0 ; i < capital . size ( ) ; i ++ ) { v . push_back ( { capital [ i ] , i } ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int j = 0 ; while ( K ) { while ( j < ( int ) capital . size ( ) && v [ j ] . first <= W ) { pq . push ( profits [ v [ j ] . second ] ) ; j ++ ; } if ( ! pq . empty ( ) ) { W = W + pq . top ( ) ; pq . pop ( ) ; } K -- ; } return W ; } int main ( ) { int K = 2 ; int W = 0 ; vector < int > P = { 1 , 2 , 3 } ; vector < int > C = { 0 , 1 , 1 } ; cout << maximizedCapital ( K , W , P , C ) ; return 0 ; }