IPO问题,最高利润

代价数组 cost[]
利润数组 profit[]
最多做 k 个项目,且项目不能并行做,也即一次之能做一个项目。也不能重复做相同项目
给出初始资金 w,求最后最大收益

------- 步骤 -------

初始化 所有项目, 项目里面包含 花费 cost 和利润 profit
准备一个小根堆,按照花费来建立,花费低的来到小根堆的头部
有初始资金 w,依次弹出小根堆的头部,但是要保证弹出的花费低于 w
将所有弹出的项目,依次按照利润 profit 排成大根堆 ----- 小根堆里是当前做不了的项目
在大根堆里面拿出头项目,这个项目就是当前可做项目中收益最高的项目,做完这个项目
由于做完了一个项目,资金变多了 w = w + p1
再在小根堆里面弹出项目,放到大根堆,再次弹出,循环流程……

package 贪心;

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

public class MostProfitIPO {

public static int findMaximizedCapital(int k, int w, int[] profits, int[] costs) {
	Node[] nodes = new Node[profits.length];
	for(int i=0;i<nodes.length;i++) {
		nodes[i] = new Node(profits[i], costs[i]);
	}
	PriorityQueue<Node> minCostHeap = new PriorityQueue<Node>(new MinCostComparator());
	PriorityQueue<Node> maxProfitHeap = new PriorityQueue<Node>(new MaxProfitComparator());
	
	//节点全部加入 代价堆
	for(int i=0;i<nodes.length;i++) {
		minCostHeap.add(nodes[i]);
	}
	
	for(int i=0;i<k;i++) {
		while(!minCostHeap.isEmpty() && minCostHeap.peek().cost <= w) {
			maxProfitHeap.add(minCostHeap.poll());
		}
		if(maxProfitHeap.isEmpty()) {
			return w;
		}
		w = w + maxProfitHeap.poll().profit;
	}
	
	return w;
}

}

class Node{
int profit;
int cost;

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

}

class MinCostComparator implements Comparator {
public int compare(Node o1, Node o2) {
return o1.cost - o2.cost;
}
}

class MaxProfitComparator implements Comparator {
public int compare(Node o1, Node o2) {
return o2.profit - o1.profit;
}
}

发布了20 篇原创文章 · 获赞 1 · 访问量 1463

猜你喜欢

转载自blog.csdn.net/weixin_44587666/article/details/89438124
IPO