|
| 1 | +classSolution { |
| 2 | +publicintfindMaximizedCapital(intk,intw,int[]profits,int[]capital) { |
| 3 | +// Max-heap for profits of affordable projects |
| 4 | +Queue<Integer>maxProfit =newPriorityQueue<>(Comparator.reverseOrder()); |
| 5 | + |
| 6 | +// Min-heap for (capital, profit) pairs |
| 7 | +Queue<int[]>minCapital =newPriorityQueue<>(Comparator.comparingInt(a ->a[0])); |
| 8 | + |
| 9 | +for (inti =0;i <capital.length;i++) { |
| 10 | +minCapital.add(newint[] {capital[i],profits[i] }); |
| 11 | + } |
| 12 | + |
| 13 | +for (inti =0;i <k;i++) { |
| 14 | +// Add all affordable projects to the maxProfit heap |
| 15 | +while (!minCapital.isEmpty() &&minCapital.peek()[0] <=w) { |
| 16 | +int[]project =minCapital.poll(); |
| 17 | +maxProfit.add(project[1]); |
| 18 | + } |
| 19 | + |
| 20 | +// If there are no affordable projects, break |
| 21 | +if (maxProfit.isEmpty()) { |
| 22 | +break; |
| 23 | + } |
| 24 | + |
| 25 | +// Select the project with the maximum profit |
| 26 | +w +=maxProfit.poll(); |
| 27 | + } |
| 28 | + |
| 29 | +returnw; |
| 30 | + } |
| 31 | +} |