动态规划
class Solution { public int maxProfit(int[] prices) { int size = prices.length; int [][] dp = new int[size][2]; dp[0][0] = -prices[0]; //不持有股票 dp[0][1] = 0; for(int i = 1; i < size; i++ ) { //多次买卖(第i天买入股票的时候,所持有的现金可能有之前买卖过的利润) dp[i][0] = Math.max(dp[i - 1][0],dp[i-1][1] - prices[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]); } return dp[size - 1][1]; }}
优化空间
class Solution {
public int maxProfit(int[] prices) {
int [] dp = new int[2];
//0表示持有,1表示卖出
dp[0] = -prices[0];
dp[1] = 0;
for(int i = 1; i < prices.length; i++ ) {
dp[0] = Math.max(dp[0],dp[1] - prices[i]);
dp[1] = Math.max(dp[1],dp[0] + prices[i]);
}
return dp[1];
}
}