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.

solution

This kind of reminds me of a problem like 621-task-scheduler, where we use two queues. The main intuition is to realize that given the amount of capital we have, we always want to take the job that gives the most profit out of the jobs that we can afford.

So, if we maintain all the jobs that we can afford in a max-heap, we can get the best job in constant time. To make sure we’re updating the max-heap, we should also maintain a second sorted structure of the projects by cost, and we can either sort or use another min-heap here.

def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
	"""
	brute force: backtrack on all possibilities -- O(n^2) w/ memoization?
	notice that given an amount of money, we always want to take the project
	we can afford to start that pays the most money
	  
	-- note that we don't need to pay a cost to start a project,
	it's just a prerequisite.
	-- if we needed to pay, this question would be harder.
	"""
	res = 0
	# max_heap on profit gained
	affordable_projects = []
	# min_heap on capital required
	remaining_projects = [(c, p) for c, p in zip(capital, profits)]
	heapify(remaining_projects)
	  
	capital = w
	for _ in range(k):
		# move all affordable projects onto heap
		while remaining_projects and remaining_projects[0][0] <= capital:
			proj_cost, proj_profit = heappop(remaining_projects)
			heappush(affordable_projects, -proj_profit)
	  
	# execute the one that gives most profit
	if affordable_projects:
		capital += -heappop(affordable_projects)
	else:
		break
 
	return capital