最多买卖两次,将股票状态设置为第一次持有,不持有,第二次持有,不持有
class Solution {
public int maxProfit(int[] prices) {
//一维
int len = prices.length;
if(prices == null || len == 0) return 0;
int[] dp = new int[5];
dp[1] = - prices[0];
dp[3] = - prices[0];
for(int i = 1; i < len; i++) {
dp[1] = Math.max(dp[1], -prices[i]);//第一次持有
dp[2] = Math.max(dp[2], dp[1] + prices[i]);//第一次不持有
dp[3] = Math.max(dp[3], dp[2] - prices[i]);//第二次持有
dp[4] = Math.max(dp[4], dp[3] + prices[i]);//第二次不持有
}
return dp[4];
}
}
class Solution {
public int maxProfit(int[] prices) {
//二维
int len = prices.length;
if(prices == null || len == 0) return 0;
int[][] dp = new int[len][5];
dp[0][1] = - prices[0];
dp[0][3] = - prices[0];
for(int i = 1; i < len; i++) {
dp[i][1] = Math.max(dp[i-1][1], -prices[i]);//第一次持有
dp[i][2] = Math.max(dp[i-1][2], dp[i-1][1] + prices[i]);//第一次不持有
dp[i][3] = Math.max(dp[i-1][3], dp[i-1][2] - prices[i]);//第二次持有
dp[i][4] = Math.max(dp[i-1][4], dp[i-1][3] + prices[i]);//第二次不持有
}
return dp[len - 1][4];
}
}
思路不太顺
股票状态,加了交易次数为k的限制,定义dp二维数组,[天数][股票状态],2*k+1,当股票状态为奇数时持有,偶数时不持有。
?
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
//dp[天数][交易次数][股票状态]
if(prices == null || len == 0) return 0;
int[][][] dp = new int[len][k+1][2];
for(int i = 0; i <= k; i ++) {
dp[0][i][1] = -prices[0];
}
for(int i = 1; i < len; i++) {
for(int j = 1; j <= k; j ++) {
dp[i][j][0] = Math.max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]);
}
}
return dp[len-1][k][0];
}
}
?
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
//dp[交易次数][股票状态]
if(prices == null || len == 0) return 0;
int[][] dp = new int[k+1][2];
for(int i = 0; i <= k; i ++) {
dp[i][1] = -prices[0];
}
for(int i = 1; i < len; i++) {
for(int j = 1; j <= k; j ++) {
dp[j][0] = Math.max(dp[j][0], dp[j][1] + prices[i]);
dp[j][1] = Math.max(dp[j][1], dp[j-1][0] - prices[i]);
}
}
return dp[k][0];
}
}
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
//dp[天数][股票状态]
if(prices == null || len == 0) return 0;
int[][] dp = new int[len][2*k+1];
for(int i = 1; i < 2 * k; i += 2) {
dp[0][i] = -prices[0];
}
for(int i = 1; i < len; i++) {
for(int j = 0; j < 2 * k; j += 2) {
dp[i][j+1] = Math.max(dp[i-1][j+1], dp[i-1][j] - prices[i]);
dp[i][j+2] = Math.max(dp[i-1][j+2], dp[i-1][j+1] + prices[i]);
}
}
return dp[len-1][2*k];
}
}