Problem
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 n
projects where the ith
project has a pure profit profits[i]
and a minimum capital of capital[i]
is needed to start it.
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.
Pick a list of at most k
distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Max heap
- We have a limited capital, and we need to pick up the projects such that we have max profit. That profit feeds into capital.
- That means we need to sort the capital array, and we can either do it by normal sorting or use min heap.
- Then we can use max heap to keep track of all available projects that have capital requirements less than or equal to capital
w
, sorted by their profits in descending order. - Then iteratively select k projects to invest in, by removing projects from the minHeap and adding them to the maxHeap as long as their capital requirements are less than or equal to W.
- Once k projects have been selected, terminate and return the total capital available, which is equal to the initial capital plus the sum of profits of the selected projects
Here is the video explanation:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- wheren
is number of projects, andk
is number of projects we choose.O(n)
to make minHeap, but then we poll out the elements from elements fromminHeap
and in worst case we can poll out elements which takesO(n log n)
, and then choosingk
projects frommaxHeap
- which requirek log n
time, as we removing 1 element from heap takeslog n
time. - 🧺 Space complexity:
O(n)
Dry Run
|
|
Initialization
minHeap
is populated with the project projects:
|
|
Choosing k projects
Iteration 1
k = 3, W = 40
Choose all the projects where capital required is below or equal to capital we have
|
|
We poll the most profitable project from maxHeap and add its profit to W.
|
|
Iteration 2
k = 2, W = 90
Choose all the projects where capital required is below or equal to capital we have:
|
|
We poll the most profitable project from maxHeap and add its profit to W.
|
|
Iteration 3
k = 1, W = 120
Choose all the projects where capital required is below or equal to capital we have:
|
|
We poll the most profitable project from maxHeap and add its profit to W.
|
|
Completion
As we have chosen all k
projects, we are done.