121. 买卖股票的最佳时机
【思路】每天只有两种状态:持有股票或者不持有股票,持有股票时又分为前一天不持有买入股票和前一天持有股票保持两种情况。不持有股票也分为前一天持有股票卖出和前一天不持有股票保持两种情况。分别选取每种状态的两种情况的最大值。
var maxProfit = function(prices) {let dp = new Array(prices.length).fill([0, 0]);dp[0] = [-prices[0], 0];for (let i = 1; i < prices.length; i++) {dp[i] = [Math.max(dp[i - 1][0], -prices[i]), // 持有股票:昨天不持有或今天买入(因为只能买入一次,所以为 -prices[i])Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]) // 不持有股票:昨天不持有或今天卖出]}return dp[prices.length - 1][1]; // 最终手里不持有股票才能收益最大化
};
122. 买卖股票的最佳时机II
【思路】这道题比上一道多了条件可以多次买入,所以递推公式有区别,其余一样。
// 贪心
var maxProfit = function(prices) {// 价格递增的话就每天买入买出let res = 0;for (let i = 1; i < prices.length; i++) {if (prices[i] - prices[i - 1] > 0) res += prices[i] - prices[i - 1];}return res;
};// 动规
var maxProfit = function(prices) {let dp = new Array(prices).fill([0, 0]);dp[0] = [-prices[0], 0];for (let i = 1; i < prices.length; i++) {dp[i] = [Math.max(dp[i - 1][1] - prices[i], dp[i - 1][0]), // 第 i 天持有:前一天不持有且 i 天买入股份或前一天不持有(因为可以多次买入,所以买入股票时等于前一天不持有股票的收益减去股票价格)Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]) // 第 i 天不持有:前一天持有且 i 天卖出或前一天不持有]}return dp[prices.length - 1][1]; // 最终手里不持有股票才能收益最大化
}
参考代码随想录:https://www.programmercarl.com/
上一篇:C数组