原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
解题思路:
对于第i
天,我们需要知道两种状态:
- 从
0
到i
天,股票最低价格,用cost
表示,即为cost = Math.min(cost, prices[i]);
- 在第
i
天卖出股票能获得的利润,用profit
表示,即为profit = prices[i] - cost
。我们可以将其与0
到i - 1
天的最大利润对比,那么遍历完成时profit
就是最大利润,即为profit = Math.max(prices[i] - cost, profit);
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let cost = prices[0]; // 从第一天到第i天买入股票的最小花费
let profit = 0; // 从第一天到第i天卖出股票的最大利润
// 从1开始遍历prices进行递推
for (let i = 1; i < prices.length; i++) {
// 到i为止已知的最小价格,是i之前已知的最小价格,与当前价格之间的较小者
cost = Math.min(cost, prices[i]);
// 到i为止产生的最大利润,是i之前产生的最大利润,与当前卖出的最大利润中的较大者
profit = Math.max(prices[i] - cost, profit);
}
// 递推到最后就得到了最大利润
return profit;
};