1. // 项目 花费 和 利润
    2. public static class Program {
    3. public int p;
    4. public int c;
    5. public Program(int p, int c) {
    6. this.p = p;
    7. this.c = c;
    8. }
    9. }
    10. // 根据花费组织的小根堆比较器
    11. public static class MinCostComparator implements Comparator<Program> {
    12. @Override
    13. public int compare(Program o1, Program o2) {
    14. return o1.c - o2.c;
    15. }
    16. }
    17. // 根据利润组织的大根堆比较器
    18. public static class MaxProfitComparator implements Comparator<Program> {
    19. @Override
    20. public int compare(Program o1, Program o2) {
    21. return o2.p - o1.p;
    22. }
    23. }
    24. // 最多K个项目
    25. // W是初始资金
    26. // Profits[] Capital[] 一定等长
    27. // 返回最终最大的资金
    28. public static int findMaximizedCapital(int K, int W, int[] Profits, int[] Capital) {
    29. PriorityQueue<Program> minCostQ = new PriorityQueue<>(new MinCostComparator());
    30. PriorityQueue<Program> maxProfitQ = new PriorityQueue<>(new MaxProfitComparator());
    31. // 先把所有的项目放入小根堆
    32. for (int i = 0; i < Profits.length; i++) {
    33. minCostQ.add(new Program(Profits[i], Capital[i]));
    34. }
    35. for (int i = 0; i < K; i++) { // 进行 k 轮
    36. //peek()获取堆顶元素但不删除
    37. // 力所能及的项目,全解锁
    38. while (!minCostQ.isEmpty() && minCostQ.peek().c <= W) {
    39. // 放入大根堆中
    40. maxProfitQ.add(minCostQ.poll());
    41. }
    42. // 没有进行k轮,但是没有能做的项目了,直接返回
    43. if (maxProfitQ.isEmpty()) {
    44. return W;
    45. }
    46. // 累加利润
    47. W += maxProfitQ.poll().p;
    48. }
    49. return W;
    50. }