Leetcode 121 Best time to buy and sell stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
動態規劃
關鍵點在於profit,最終的最優解,即為在每步最優解中取最優解
建立一個profits陣列儲存每天最優解,最終選擇最優解,當然這裡要時刻跟蹤最小值。
var maxProfit = function(prices) { var profits = []; var minPrice = prices[0]; for (let i = 0; i < prices.length; i++) { minPrice = Math.min(minPrice, prices[i]); profits[i] = prices[i] - minPrice; } return Math.max(...profits); };
優化後:
var maxProfit = function(prices) { var minPrice = Number.MAX_VALUE, maxProfit = 0; for (var i = 0; i < prices.length; i++) { minPrice = Math.min(minPrice, prices[i]); var profit = prices[i] - minPrice; maxProfit = Math.max(maxProfit, profit); } return maxProfit; };