IPO

标签: 贪心 数组 排序 堆(优先队列)

难度: Hard

假设 力扣(LeetCode)即将开始 IPO 。为了以更高的价格将股票卖给风险投资公司,力扣 希望在 IPO 之前开展一些项目以增加其资本。 由于资源有限,它只能在 IPO 之前完成最多 k 个不同的项目。帮助 力扣 设计完成最多 k 个不同项目后得到最大总资本的方式。

给你 n 个项目。对于每个项目 i ,它都有一个纯利润 profits[i] ,和启动该项目需要的最小资本 capital[i]

最初,你的资本为 w 。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。

总而言之,从给定项目中选择 最多 k 个不同项目的列表,以 最大化最终资本 ,并输出最终可获得的最多资本。

答案保证在 32 位有符号整数范围内。

示例 1:

输入:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
输出:4
解释:
由于你的初始资本为 0,你仅可以从 0 号项目开始。
在完成后,你将获得 1 的利润,你的总资本将变为 1。
此时你可以选择开始 1 号或 2 号项目。
由于你最多可以选择两个项目,所以你需要完成 2 号项目以获得最大的资本。
因此,输出最后最大化的资本,为 0 + 1 + 3 = 4。

示例 2:

输入:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
输出:6

提示:

  • 1 <= k <= 105
  • 0 <= w <= 109
  • n == profits.length
  • n == capital.length
  • 1 <= n <= 105
  • 0 <= profits[i] <= 104
  • 0 <= capital[i] <= 109

Submission

运行时间: 70 ms

内存: 36.9 MB

import heapq
class Solution:
    def findMaximizedCapital(
        self, k: int, w: int, profits: List[int], capital: List[int]
    ) -> int:
        if w >= max(capital):
            return w+sum(sorted(profits)[-k:])
        n=len(profits)
        current=0
        items=list(zip(capital,profits))
        items.sort(key=lambda x:x[0])
        heap=[]
        for _ in range(k):
            while current < n and items[current][0] <= w:
                heapq.heappush(heap,-items[current][1])
                current+=1
            if not heap:
                break
            w-=heapq.heappop(heap)
        return w

Explain

This solution uses a greedy algorithm combined with a priority queue (heap) to efficiently select projects that maximize capital. Initially, it checks if the starting capital 'w' is greater than or equal to the highest capital requirement among the projects. If this is the case, it sorts the profits in descending order and picks the top 'k' to get the maximum profit immediately. Otherwise, it pairs each project with its capital and profit, sorts these pairs based on capital, and then uses a max-heap to keep track of the most profitable projects that can be started with the current capital. In each iteration (up to 'k' times), it pushes all feasible projects (based on current capital) into the heap and then selects the project with the highest profit. The profit of the selected project is added to the capital, and this process repeats until 'k' projects are completed or no further projects can be initiated.

时间复杂度: O(n log n)

空间复杂度: O(n)

import heapq
class Solution:
    def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
        if w >= max(capital):
            # If initial capital is greater than all project requirements, sort and pick the top k profitable projects
            return w + sum(sorted(profits)[-k:])
        n = len(profits)
        current = 0
        items = list(zip(capital, profits))
        items.sort(key=lambda x: x[0])  # Sort projects by capital requirement
        heap = []
        for _ in range(k):
            while current < n and items[current][0] <= w: # Push feasible projects to max-heap
                heapq.heappush(heap, -items[current][1]) # Use negative to simulate a max-heap using min-heap
                current += 1
            if not heap:
                break
            w -= heapq.heappop(heap)  # Pop the project with the max profit
        return w

Explore

如果初始资本大于所有项目的资本要求,选择利润最高的k个项目是最优的。因为所有项目都已经可以立即启动,没有资本限制,因此直接选择最高利润的项目将直接最大化初始投资回报。没有更复杂的策略会在这种情况下产生更高的利润,因为更高的利润项目已经被包括在被选择的项目中。

贪心算法结合优先队列在大多数情况下都是有效的,但不能保证在所有情况下都是最优的。这种方法在每一步都选择当前可行的最高利润项目,这通常会导致资本的快速增长。然而,在一些特殊情况下,可能存在一种选择较小利润但后续项目的总利润更高的策略。但这种情况在实际应用中较为罕见,且难以在多项选择中直接识别和计算。

将项目按资本要求排序的目的是快速确定哪些项目在当前资本下是可行的。这样做可以高效地过滤掉当前无法启动的项目,减少每次迭代的计算量。而使用最大堆(优先队列)来选择最高利润的项目的目的是确保每次都能从所有可行的项目中选出利润最大的一个。这种结合使用的方法,通过排序保证项目可行性的快速检查,通过最大堆实现利润最大化的快速选择,两者互补,提高了整体的执行效率和效果。

Python标准库中的heapq模块仅提供了最小堆的实现,并没有直接提供最大堆的功能。通过将元素的符号取反,可以利用最小堆来实现最大堆的效果。这种方法简单有效,避免了引入额外的数据结构或复杂的封装,保持代码的简洁和高效。在性能敏感或者代码简洁性重要的情况下,这种方法是一个很好的选择。