1public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
2 // Sort projects by capital
3 int n = profits.length;
4 int[][] projects = new int[n][2];
5 for (int i = 0; i < n; i++) {
6 projects[i] = new int[]{capital[i], profits[i]};
7 }
8 Arrays.sort(projects, (a, b) -> a[0] - b[0]);
9
10 PriorityQueue<Integer> maxHeap = new PriorityQueue<>(
11 (a, b) -> b - a
12 );
13 int i = 0;
14
15 for (int j = 0; j < k; j++) {
16 // Add all affordable projects to heap
17 while (i < n && projects[i][0] <= w) {
18 maxHeap.offer(projects[i][1]);
19 i++;
20 }
21
22 // If no projects available, break
23 if (maxHeap.isEmpty()) {
24 break;
25 }
26
27 // Take most profitable project
28 w += maxHeap.poll();
29 }
30
31 return w;
32}