• 贪心算法-IPO问题


    1、题目描述
    给你一个启动资金w,和一个最大项目次数k。
    然后,有两个数组,一个cost[],里面记录了每个项目需要花费的资金。一个profit数组,里面记录了每个项目完成后可以获取的利润。然后请你计算出,给你一个初始资金w,和最大项目次数k的情况下,可以获取的最大利润。每次只能做一个项目,不能同时进行几个项目。
    例如:初始资金10,k=3,cost[10,20,30,40],profit[10,20,30,40]
    那么,初始资金只能够花费来进行第一个10的项目,其他项目买不起,然后,第一个项目做完,利润是10,现在手里有20,就可以进行第二个项目了,然后再累加利润,看看能不能再解锁新项目。注意,每个项目只能做一次。

    2、思路解析

    升级打怪思路,就是我来到新手村,我肯定是找自己能干的过的,并且对我能力值提升高的怪物来打
    就是搞两个堆小根堆+大根堆
    小根堆里放所有项目 按项目花费资金排序
    大根堆里放所有当前资金能覆盖的项目,按利润排序
    最后把大根堆弹出的项目的利润加在一起即为所得

    代码实现

    // 最多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++) {
          while (!minCostQ.isEmpty() && minCostQ.peek().c <= W) {
             maxProfitQ.add(minCostQ.poll());
          }
          //可能资本不足,造成现在还能做项目但是大根堆没有项目给你做了
          if (maxProfitQ.isEmpty()) {
             return W;
          }
          W += maxProfitQ.poll().p;
       }
       return W;
    }
    
    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;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
  • 相关阅读:
    【图像分类】2022-RepLKNet CVPR 31x31卷积了解一下
    好消息,完整版的jwt鉴权机制来了呦
    华为---OSPF协议优先级、开销(cost)、定时器简介及示例配置
    Git 版本控制
    WeChat Subscribers Lite - 微信公众订阅号自动回复WordPress插件
    学信息系统项目管理师第4版系列26_项目绩效域(下)
    Python初级练习小实例(1-20例),1个实例多个例子相互参考
    torch(四)、Serialization
    【leetcode 力扣刷题】栈—波兰式///逆波兰式相关知识和题目
    [Python] zip()函数
  • 原文地址:https://blog.csdn.net/m0_37900506/article/details/133148478