LeetCode 经典 150 · 可视化
逐步动画、变量流转与五语言代码参考
#122 · 数组 / 字符串
买卖股票的最佳时机 II
Best Time to Buy and Sell Stock II
prices = [7,1,5,3,6,4]线性序列4 个关键状态
步骤 1价格下跌,不交易。
profit=07
01
15
23
36
44
5推荐
累加所有上涨
时间
O(n)空间 O(1)每一段上涨都可以拆成相邻两天的利润,正差价全部收入即可。
1function maxProfit(prices) {2 let profit = 0;3 for (let i = 1; i < prices.length; i++) {4 profit += Math.max(0, prices[i] - prices[i - 1]);5 }6 return profit;7}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 public int maxProfit(int[] prices) {3 int ans = 0;4 for (int i = 1; i < prices.length; ++i) {5 ans += Math.max(0, prices[i] - prices[i - 1]);6 }7 return ans;8 }9}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。