LeetCode IPO

原题链接在这里:https://leetcode.com/problems/ipo/description/

题目:

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 project i, 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.

题解:

找出每次在现有capital内最大profit的project.

利用两个heap 保存 capital 和 profit的对, 一个 min heap 从小到大按照capital保存. 一个max heap从大到小按照profit保存.

比现有capital小的所有对都从 min heap中poll出来加到max heap里, 顶头的就是小于capital最大profit的project.

Time Complexity: O(k*logn). n = Profits.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {
 3         PriorityQueue<int []> capMinHeap = new PriorityQueue<int []>((a,b) -> a[0]-b[0]);
 4         PriorityQueue<int []> proMaxHeap = new PriorityQueue<int []>((a,b) -> b[1]-a[1]);
 5         
 6         for(int i = 0; i<Profits.length; i++){
 7             capMinHeap.add(new int[]{Capital[i], Profits[i]});
 8         }
 9         
10         for(int i = 0; i<k; i++){
11             while(!capMinHeap.isEmpty() && capMinHeap.peek()[0]<=W){
12                 proMaxHeap.add(capMinHeap.poll());
13             }
14             
15             if(proMaxHeap.isEmpty()){
16                 break;
17             }
18             
19             W += proMaxHeap.poll()[1];
20         }
21         
22         return W;
23     }
24 }

 

posted @ 2017-10-28 07:29  Dylan_Java_NYC  阅读(245)  评论(0编辑  收藏  举报