Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Parikshit Murria
Easy to Understand Solution With Similar Approach

Parikshit Murria

Apr 2, 2025

import java.util.*; class Solution { public static int findMaximumCapital(int[] capital, int[] profits,int numberOfProjects, int initialCapital) { //Two Queues MinHeap for Capital and MaxHeap for Profit Queue<int[]> capitalHeap = new PriorityQueue<>((a,b) -> a[0] - b[0]); Queue<int[]> profitHeap = new PriorityQueue<>((a,b) -> b[1] - a[1]); //Popoulate Capital Heap with array objects containing both capital and profit. for (int i=0; i<capital.length; i++) { int [] temp = new int[2]; temp[0] = capital[i]; temp[1] = profits[i]; capitalHeap.offer(temp); } //Initialize count and totalCapital int count = 0; int totalCapital = initialCapital; //Run till the required numberOfProjects are picked while(count < numberOfProjects) { //Pick all the prjects that can be picked with current totalCapital. while(!capitalHeap.isEmpty() && capitalHeap.peek()[0] <= totalCapital) { //Add these feasible projects to profit heap. profitHeap.offer(capitalHeap.poll()); } if (profitHeap.isEmpty()) { break; } // Pick the topmost profit from max heap. This will ensure out of all feasible projects we are picking // the one with max profit totalCapital += profitHeap.poll()[1]; //Increment the count for picked projects. count++; } return totalCapital; } }

0

0

Comments
Comments

On this page