题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
DP思想:
1. 记录【今天之前买入的最小值】,是为了在最小值买
2. 计算【今天之前最小值买入,可以获得的利润】,这便是今天卖出的话的最大利润
3. 比较【每天的最大利润】,取最大值
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if(prices.length <= 1) return 0;
let min = prices[0], max = 0;
for(let i = 1;i < prices.length;i++){
max = Math.max(max,prices[i]-min); //只需要和min相减
min = Math.min(min,prices[i]);
}
return max;
};

本文介绍了一个经典的股票交易问题,通过动态规划的思想找到买入和卖出的最佳时机以获得最大利润。使用一个变量记录到当前为止的最低购买价格,并用另一个变量跟踪以此最低价格买入后可能获得的最大利润。
209

被折叠的 条评论
为什么被折叠?



