输入:参数1:正数数组costs (成本);参数2:正数数组profits (纯利润) ;参数3:正数k ;参数4:正数m
costs[i]表示i号项目的花费,profits[i]表示i号项目在扣除花费之后还能挣到的钱(利润),k表示你不能并行、只能串行的最多做k个项目,m表示你初始的资金
说明:你每做完一个项目,马上获得的收益,可以支持你去做下 一个项目。
输出: 你最后获得的最大钱数。
思路 建立小根堆(依据costs排序);将所有能用当前本金m完成的项目移到大根堆(依据profits排序)中;择取大根堆的头节点;本金m变为本金m+利润profits。
package algorithm.section7;
import java.util.Comparator;
import java.util.PriorityQueue;
public class IPO {
public static class Project{
public int cost;
public int profit;
public Project(int cost, int profit) {
this.cost = cost;
this.profit = profit;
}
}
public static class CostComparator implements Comparator<Project> {
@Override
public int compare(Project project1, Project project2) {
return project1.cost - project2.cost;
}
}
public static class ProfitComparator implements Comparator<Project>{
@Override
public int compare(Project project1, Project project2) {
return project2.profit - project1.profit;
}
}
public static int mostMoney(Project[] projects, int money, int pros){
if (projects.length == 0) return 0;
int num = money;
PriorityQueue<Project> costs = new PriorityQueue<>(new CostComparator());
for (Project project : projects) costs.add(project);
PriorityQueue<Project> profits = new PriorityQueue<>(new ProfitComparator());
for (int i = 0; i < pros; i++) {
while (!costs.isEmpty() && costs.peek().cost <= num)
profits.add(costs.poll());
if (!profits.isEmpty()) num += profits.poll().profit;
else return num;
}
return num;
}
public static void main(String[] args){
int pros = 4;
int money = 7;
Project[] projects = new Project[4];
projects[0] = new Project(5, 3);
projects[1] = new Project(10, 2);
projects[2] = new Project(6, 4);
projects[3] = new Project(20, 9);
System.out.println(mostMoney(projects, money, pros));
}
}