题目描述:
示例 1:
示例 2:
题目描述:
- 最多投资k次
- 初始资本为w,后续资本为w += profits[i]
- 求k次之后的最大w.
思路:
需要保证最终w最大,可以通过保证每次投资之后w最大,因为下次w = w + profits[i],因此只要保证每次投资时,profits[i]是当前能获取的最大值,即可保证w为最大值。
代码实现:
class Solution {
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = profits.length;
List<int[]> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(new int[]{capital[i], profits[i]});
}
Collections.sort(list, (a,b)->a[0]-b[0]);
PriorityQueue<Integer> q = new PriorityQueue<>((a,b)->b-a);
int i = 0;
while (k-- > 0) {
while (i < n && list.get(i)[0] <= w) q.add(list.get(i++)[1]);
if (q.isEmpty()) break;
w += q.poll();
}
return w;
}
}