链接
题目描述
思路
代码
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int n = prices.length;
int[][] dp = new int[n][2];
for(int i = 0; i < n ;i++){
if(i == 0){
dp[i][0] = 0;
//max(-infinity,-prices[i])
dp[i][1] = -prices[i];
continue;
}
if(i == 1){
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1] = Math.max(-prices[0],-prices[1]);
continue;
}
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-2][0]-prices[i]);
}
return dp[n-1][0];
}
}