做项目的最大收益问题

import java.util.Comparator;
import java.util.PriorityQueue;

public class Test01 {

    //数据结构 -> 我要使用 这个结构作为我的 参数类型
         //项目
    class Program{
        private int cost;//这个项目 需要花费多少钱
        private int profit;//这个项目 有多少利益

        public Program(int cost, int profit) {
            this.cost = cost;
            this.profit = profit;
        }
    }

    //小根堆比较器
    class CostMinComparator  implements Comparator<Program>{

        @Override
        public int compare(Program o1, Program o2) {
            return o1.cost-o2.cost;
        }
    }
    //大根堆比较器
    class ProfitMaxComparator implements Comparator<Program>{

        @Override
        public int compare(Program o1, Program o2) {
            return o2.profit- o1.profit;
        }
    }
    /**
     *
     * @param W 代表启动资金
     * @param K  代表 可以做 K 个项目
     * @param costs   代表 每个项目需要 花费 的钱数
     * @param profits  代表 每个项目所得利益
     */
    public  int getMaxMoney(int W,int K,int[] costs,int[] profits){
        if(W<1||K<0||costs==null||profits==null||costs.length!=profits.length){
            return W;
        }
        //按照 项目花费的钱 构成小根堆
        PriorityQueue<Program> costMinHeap=new PriorityQueue<>(new CostMinComparator());
        //按照 项目所得利益 形成 大根堆
        PriorityQueue<Program> profitMaxHeap=new PriorityQueue<>(new ProfitMaxComparator());

        //先将 所有的项目 花费的钱 按照小根堆的逻辑加入 到小跟堆
        for (int i = 0; i < costs.length; i++) {
            //注意 堆里面存放的是项目 , 现在没有 项目 所有要创建项目
            costMinHeap.add(new Program(costs[i],profits[i]));
        }
        //要 做 K 个 项目
        for (int i = 1; i <=K ; i++) {

            //1.将 小根堆里面的 从堆顶 开始 花费的钱比 启动资金 小的 进入大根堆中
             //1.1 除非 小根堆没有项目了 或者 当前项目花费的 钱 比启动资金大  都进入大根堆中
            while (!costMinHeap.isEmpty()&&costMinHeap.peek().cost<=W){
                profitMaxHeap.add(costMinHeap.poll());
            }
            // 如果 大根堆 里面是空的 说明 没有项目可以做, 直接返回 启动资金
             if(profitMaxHeap.isEmpty()){
                return W;
            }
             //否则有项目可以做
            W+=profitMaxHeap.poll().profit;
        }
        return W;
    }

    public static void main(String[] args) {

        Test01 t=new Test01();
        int W=3;
        int K=2;
        int[] costs={5,4,1,2};
        int[] profit={3,5,3,2};
        int maxMoney = t.getMaxMoney(W, K, costs, profit); //11
        System.out.println(maxMoney);

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值