Algorithms first

IPO · 交互式算法学习

最多完成 k 个项目,使最终资本最大。

#502 ·

IPO

IPO

测试用例k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
栈 / 队列 / 堆3 个关键状态
步骤 1资本 0 的项目利润 1 入堆。heap=[1]
c0/p1c1/p2c1/p3
推荐

资本排序 + 最大堆利润

时间 O(n log n+k log n)空间 O(n)

按资本排序,把当前可做项目利润加入最大堆,每轮弹最大利润。

1function findMaximizedCapital(k, w, p, c) {2  const projects = c.map((x, i) => [x, p[i]]).sort((a, b) => a[0] - b[0]),3    heap = [];4  const push = x => {5    heap.push(x);6    let i = heap.length - 1;7    while (i) {8      const p = (i - 1) >> 1;9      if (heap[p] >= heap[i]) break;10      [heap[p], heap[i]] = [heap[i], heap[p]];11      i = p12    }13  };14  const pop = () => {15    const top = heap[0],16      last = heap.pop();17    if (heap.length) {18      heap[0] = last;19      for (let i = 0;;) {20        let best = i,21          l = i * 2 + 1,22          r = l + 1;23        if (l < heap.length && heap[l] > heap[best]) best = l;24        if (r < heap.length && heap[r] > heap[best]) best = r;25        if (best === i) break;26        [heap[i], heap[best]] = [heap[best], heap[i]];27        i = best28      }29    }30    return top31  };32  let i = 0;33  while (k--) {34    while (i < projects.length && projects[i][0] <= w) push(projects[i++][1]);35    if (!heap.length) break;36    w += pop()37  }38  return w;39}
多语言参考

Java · C++ · Go

来源 · CC BY-SA 4.0 ↗

这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。

1class Solution {2    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {3        int n = capital.length;4        PriorityQueue<int[]> q1 = new PriorityQueue<>((a, b) -> a[0] - b[0]);5        for (int i = 0; i < n; ++i) {6            q1.offer(new int[] {capital[i], profits[i]});7        }8        PriorityQueue<Integer> q2 = new PriorityQueue<>((a, b) -> b - a);9        while (k-- > 0) {10            while (!q1.isEmpty() && q1.peek()[0] <= w) {11                q2.offer(q1.poll()[1]);12            }13            if (q2.isEmpty()) {14                break;15            }16            w += q2.poll();17        }18        return w;19    }20}
交互式算法学习

从执行步骤真正理解 LeetCode 经典 150

本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。

多形态可视化数组、矩阵、DP 表、递归树、树图、链表、栈队列堆、区间和状态机按解法选择。
动画与代码同步当前状态、步骤说明、变量和代码高亮保持一一对应,可逐步播放和回退。
适合面试复习每种方案都给出思路、时间复杂度、空间复杂度、测试用例和 LeetCode 中文原题入口。
AlgoViz Lab

IPO · 解法对比

最多完成 k 个项目,使最终资本最大。

测试用例
k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
题目分类
解法对比
2
方案 1

每轮扫描所有可做项目

每轮在未选且资本要求满足的项目中找最大利润。

时间
O(kn)
空间
O(n)
方案 2

资本排序 + 最大堆利润

按资本排序,把当前可做项目利润加入最大堆,每轮弹最大利润。

时间
O(n log n+k log n)
空间
O(n)