IPO issue, the highest profit

The cost of the array cost []
profit Array profit []
do most k project, and the project can not be done in parallel, that is the time to do a project. Can not repeat the same items
are given initial capital w, finally seeking the maximum benefit

Step ------- -------

Initialize all projects, projects which include spending cost profit profit and
prepare a little heap root, in accordance with the cost to build, low cost heap head came rootlets
have initial capital w, followed by the head of the pop heap of small roots, but to guarantee the pop-up cost of less than w
all the pop-up items, profit profit following sequentially arranged in a large root heap ----- small pile root is the current projects do not
come up with the first project in a large root heap inside, this project is currently to do the project in the highest yielding projects to finish this project
due to finish a project, funding becomes more w = w + p1
again in a small pop-up root inside the reactor project, into a big pile roots, pop-up again, the cycle process ......

package greedy;

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

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

Published 20 original articles · won praise 1 · views 1463

Guess you like

Origin blog.csdn.net/weixin_44587666/article/details/89438124