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);
}
}