public class Solution { public static int maxProfit(int[] prices) { int length=prices.length; if(length==0)return 0; //dp[][][1]是持有股票时j //dp[][][0]是不持有股票时 //dp[][j][]是第几次交易 int dp[][][]=new int[length][3][2]; for(int i=0;i<length;i++) for(int j=1;j<3;j++) for(int z=1;z<2;z++) { dp[i][j][z]=-100000; } dp[0][1][1]=-prices[0]; for(int i=1;i<length;i++) for(int j=1;j<3;j++) { //第i天的第j次交易不持有股票由第i-1天的第j次交易不持有股票和第i-1天的持有股票第j次交易持有股票 dp[i][j][0]=Math.max(dp[i-1][j][0],dp[i-1][j][1]+prices[i]); //第i天的第j次交易持有股票由第i-1天的第j次交易持有股票和第i-1天的第j-1次交易不持有股票 dp[i][j][1]=Math.max(dp[i-1][j][1],dp[i-1][j-1][0]-prices[i]); } return Math.max(dp[length-1][1][0],dp[length-1][2][0]); } }