leetcode502. IPO

题目要求

Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.

You are given several projects. For each projecti, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.

To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital.

Example 1:

Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].

Output: 4

Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.

Note:

  1. You may assume all numbers in the input are non-negative integers.
  2. The length of Profits array and Capital array will not exceed 50,000.
  3. The answer is guaranteed to fit in a 32-bit signed integer.

假设现在团队最多能够完成k个项目,每个项目分别被标记了所需要投入的资本capital和最后生成的纯利润profit,已知团队初始时有W的初始资金,问按照什么顺序完成项目从而得到最大的利润,返回最终团队的资金数量。

思路和代码

这个其实和操作系统中针对现成死锁预测的银行家算法很像。银行家算法的就在于尝试分配当前的资源给多个需要该资源的线程,如果能够找到一个发放序列成功的满足所有线程的要求,则说明不会导致死锁。而这里也是同样,为了达到最大的效益,这意味着每次都要用有限的资本来获得最高的利润。因此我们要选择合适的数据结构,使得我们先快速筛选出能够投资的所有项目,再选择一个利润最高的项目进行执行。

代码中有两种实现方式,一种是利用两个优先队列,一个优先队列用于将队列中的项目按照所需资金从小到大进行排序,而另一个优先队列则用于将队列中的项目按照获得利润从大到小进行排序。现将所有的项目假如资金优先队列中,并取出当前所有可以执行的项目放入利润优先队列中,此时利润优先队列中取出来的第一个项目就是利润最高的可执行项目。按照这个执行顺序继续执行,直到完成了要求的K个项目。

public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {  
    PriorityQueue<Integer> capitalQueue = new PriorityQueue<>(Comparator.comparingInt(o -> Capital[o]));  
    PriorityQueue<Integer> profitQueue = new PriorityQueue<>((o1, o2) -> Profits[o2] - Profits[o1\]);  
  
    IntStream.range(0, Capital.length).forEach(capitalQueue::offer);  
  
    while (k-- != 0) {  
        while (!capitalQueue.isEmpty() &&  Capital[capitalQueue.peek()] <= W) {  
            profitQueue.offer(capitalQueue.poll());  
        }  
        if (profitQueue.isEmpty()) {  
            break;  
        }  
        W += Profits[profitQueue.poll()];  
    }  
    return W;  
}

还有一种方式就是对所有的项目先按照利润排序,再按照资本排序。这样从优先队列中顺序选出的第一个能够完成的项目就是当前完成的最优项目。这里需要把当前不能完成的项目放回优先队列。

public int findMaximizedCapital2(int k, int W, int[] Profits, int[] Capital) {  
    int length = Profits.length;  
    k = Math.min(k, length);  
    PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){  
        @Override  
  public int compare(int[] a, int[] b) {  
            int p = b[0] - a[0];  
            if (p == 0) return a[1] - b[1];  
            return p;  
        }  
    });  
  
    for (int i = 0; i < length; i++) pq.add(new int[] {Profits[i], Capital[i]});  
    for (int i = 0; i < k; i++) {  
        List<int[]> scanned = new ArrayList<>();  
        int mark = pq.size();  
        while (pq.size() > 0) {  
            int[] check = pq.poll();  
            if (check[1] <= W) {  
                W += check[0];  
                break;  
            } else {  
                scanned.add(check);  
            }  
        }  
        if (scanned.size() == mark) break;  
        pq.addAll(scanned);  
    }  
  
    return W;  
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 395. Longest Substring with At Least K Repeating Characters

    这是一个经典的分治法解决的问题,关键在于我们如何将这个问题分解为更小的子问题。反过来想,这个子字符串一定不包含什么元素呢?当一个元素出现的总次数小于k,那么该元...

    眯眯眼的猫头鹰
  • leetcode363. Max Sum of Rectangle No Larger Than K

    现有一个由整数构成的矩阵,问从中找到一个子矩阵,要求该子矩阵中各个元素的和为不超过k的最大值,问子矩阵中元素的和为多少? 注:后面的文章中将使用[左上角顶点坐标...

    眯眯眼的猫头鹰
  • leetcode480. Sliding Window Median

    Median is the middle value in an ordered integer list. If the size of the list i...

    眯眯眼的猫头鹰
  • HDUOJ---2642Stars(二维树状数组)

    Stars Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/65536 K (Jav...

    Gxjun
  • HDU 5652 India and China Origins(并查集)

    India and China Origins Time Limit: 2000/2000 MS (Java/Others)    Memory Limit:...

    ShenduCC
  • Gym 100952I&&2015 HIAST Collegiate Programming Contest I. Mancala【模拟】

    I. Mancala time limit per test:3 seconds memory limit per test:256 megabytes inp...

    Angel_Kitty
  • 洛谷P2863 [USACO06JAN]牛的舞会The Cow Prom

    ng the other ends of her ropes (if she has any), along with the cows holding the...

    attack
  • POJ 1163(数字三角形)

    7 3 8 8 1 0 2 7 4 4 4 5 2 6 5

    AI那点小事
  • 230B. T-primes (数论)

    We know that prime numbers are positive integers that have exactly two distinct ...

    dejavu1zz
  • Codeforces 833E Caramel Clouds

    E. Caramel Clouds time limit per test:3 seconds memory limit per test:256 megaby...

    Angel_Kitty

扫码关注云+社区

领取腾讯云代金券