java 502. IPO(一堆).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 502. IPO(一堆).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {
        PriorityQueue<int[]> candidates = new PriorityQueue<int[]>( new Comparator<int[]>() {
                public int compare(int[] a, int[] b) {
                    return a[0] - b[0];
                }
        });
        
        PriorityQueue<int[]> maxHeap = new PriorityQueue<int[]> (new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return b[1] - a[1];
            }
        });
        
        for (int i = 0; i < Profits.length; i++) {
            candidates.offer(new int[] {Capital[i], Profits[i]});
        }
        
        for (int i = 0; i < k; i++) {
            while (!candidates.isEmpty() && W >= candidates.peek()[0]) {
                maxHeap.offer(candidates.poll());
            }
            if (maxHeap.isEmpty()) break;
            W += maxHeap.poll()[1];
        }
        return W;
    }
}
public class Solution {
    class Pair {
        int profit;
        int capital;
        public Pair (int profit, int capital) {
            this.profit = profit;
            this.capital = capital;
        }
    }
    public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {
        PriorityQueue<Pair> heap = new PriorityQueue<Pair>(new Comparator<Pair>() {
            public int compare(Pair p1, Pair p2) {
                if (p1.profit == p2.profit) return p1.capital - p2.capital;
                return p2.profit - p1.profit;
            }
        });
        for (int i = 0; i < Capital.length; i++) {
            heap.add(new Pair(Profits[i], Capital[i]));
        }
        for (int i = 0; i < k; i++) {
            List<Pair> tmp = new ArrayList<Pair>();
            while (!heap.isEmpty() && heap.peek().capital > W) {
                tmp.add(heap.poll());
            } 
            if (heap.size() == 0) break;
            W += heap.peek().profit;
            heap.poll();
            if (tmp.size() != 0) {
                for (Pair p : tmp) {
                    heap.add(p);
                }
            }
        }
        return W;
    }
}

以上是关于java 502. IPO(一堆).java的主要内容,如果未能解决你的问题,请参考以下文章

java 502. IPO(一堆).java

java 502. IPO(一堆).java

java 502. IPO(一堆).java

java 502. IPO(一堆).java

✨贪心+大根堆解决——>力扣502. IPO

贪心+优先队列502. IPO