LeetCode309. 最佳买卖股票时机含冷冻期
作者:互联网
class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int len = prices.length; int[][] dp = new int[len][3]; // dp[i][j] 到第 i 天结束不同状态的最大收益 // j = 0 : 未持股且不是冷冻期 j = 1 : 持股 j = 2 : 冷冻期(今天卖出,不持股) dp[0][1] = -prices[0]; for (int i = 1; i < len; i++) { dp[i][0] = Math.max(dp[i-1][0], dp[i-1][2]); dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); dp[i][2] = dp[i-1][1] + prices[i]; } return Math.max(dp[len-1][0], dp[len-1][2]); // 空间优化 /* int dp0 = 0, dp2 = 0; int dp1 = -prices[0]; for (int i = 1; i < len; i++) { int newDp0 = Math.max(dp0, dp2); int newDp1 = Math.max(dp1, dp0 - prices[i]); int newDp2 = dp1 + prices[i]; dp0 = newDp0; dp1 = newDp1; dp2 = newDp2; } return Math.max(dp0, dp2); */ } }
标签:int,max,LeetCode309,len,最佳,Math,prices,冷冻,dp 来源: https://www.cnblogs.com/HuangYJ/p/14217119.html