Maximum amount of capital required for selecting at most K projects | java 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 ; Add 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
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int maximizedCapital ( int K , int W , int profits [ ] , int capital [ ] ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( Collections . reverseOrder ( ) ) ; ArrayList < int [ ] > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < capital . length ; i ++ ) { v . add ( new int [ ] { capital [ i ] , i } ) ; } Collections . sort ( v , ( a , b ) -> { if ( a [ 0 ] != b [ 0 ] ) return a [ 0 ] - b [ 0 ] ; return a [ 1 ] - b [ 1 ] ; } ) ; int j = 0 ; while ( K != 0 ) { while ( j < capital . length && v . get ( j ) [ 0 ] <= W ) { pq . add ( profits [ v . get ( j ) [ 1 ] ] ) ; j ++ ; } if ( ! pq . isEmpty ( ) ) { W = W + pq . peek ( ) ; pq . poll ( ) ; } K -- ; } return W ; } public static void main ( String [ ] args ) { int K = 2 ; int W = 0 ; int P [ ] = { 1 , 2 , 3 } ; int C [ ] = { 0 , 1 , 1 } ; System . out . println ( maximizedCapital ( K , W , P , C ) ) ; } }