题解 | #做项目的最大收益问题#
做项目的最大收益问题
http://www.nowcoder.com/practice/cbe887812d3041669fc93a0cf5235f63
import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static class Program { public int cost; public int profit; public Program(int cost, int profit) { this.cost = cost; this.profit = profit; } } //定义小根堆如何比较大小 public static class costMinComp implements Comparator<Program> { @Override public int compare(Program o1, Program o2) { return o1.cost - o2.cost; } } //定义大根堆如何比较大小 public static class costMaxComp implements Comparator<Program> { @Override public int compare(Program o1, Program o2) { return o2.profit - o1.profit; } } public static long getMaxMoney(long W, long K, int[] costs, int[] profits) { if (W < 1 || K < 0 || costs == null || profits == costs || costs.length != profits.length) { return W; } PriorityQueue<Program> costMinHeap = new PriorityQueue<>(new costMinComp()); PriorityQueue<Program> profitMaxHeap = new PriorityQueue<>(new costMaxComp()); for (int i = 0; i < costs.length; i++) { costMinHeap.add(new Program(costs[i], profits[i])); } //依次做K个项目 for (int i = 1; i <=K ; i++) { 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) { Scanner in=new Scanner(System.in); String[] strings=in.nextLine().split(" "); int n=Integer.parseInt(strings[0]); int W=Integer.parseInt(strings[1]); int K=Integer.parseInt(strings[2]); int[] costs=new int[n]; int[] profits=new int[n]; for (int i = 0; i <n ; i++) { costs[i]=in.nextInt(); } for (int i = 0; i <n ; i++) { profits[i]=in.nextInt(); } long res=getMaxMoney(W,K,costs,profits); System.out.println(res); } }