// 项目 花费 和 利润
public static class Program {
public int p;
public int c;
public Program(int p, int c) {
this.p = p;
this.c = c;
}
}
// 根据花费组织的小根堆比较器
public static class MinCostComparator implements Comparator<Program> {
@Override
public int compare(Program o1, Program o2) {
return o1.c - o2.c;
}
}
// 根据利润组织的大根堆比较器
public static class MaxProfitComparator implements Comparator<Program> {
@Override
public int compare(Program o1, Program o2) {
return o2.p - o1.p;
}
}
// 最多K个项目
// W是初始资金
// Profits[] Capital[] 一定等长
// 返回最终最大的资金
public static int findMaximizedCapital(int K, int W, int[] Profits, int[] Capital) {
PriorityQueue<Program> minCostQ = new PriorityQueue<>(new MinCostComparator());
PriorityQueue<Program> maxProfitQ = new PriorityQueue<>(new MaxProfitComparator());
// 先把所有的项目放入小根堆
for (int i = 0; i < Profits.length; i++) {
minCostQ.add(new Program(Profits[i], Capital[i]));
}
for (int i = 0; i < K; i++) { // 进行 k 轮
//peek()获取堆顶元素但不删除
// 力所能及的项目,全解锁
while (!minCostQ.isEmpty() && minCostQ.peek().c <= W) {
// 放入大根堆中
maxProfitQ.add(minCostQ.poll());
}
// 没有进行k轮,但是没有能做的项目了,直接返回
if (maxProfitQ.isEmpty()) {
return W;
}
// 累加利润
W += maxProfitQ.poll().p;
}
return W;
}