121. 买卖股票的最佳时机
class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1;i<prices.length;i++){
dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
dp[i][1] = Math.max(dp[i-1][1], prices[i]+dp[i-1][0]);
}
return dp[prices.length-1][1];
}
}
122.买卖股票的最佳时机II
class Solution {
public int maxProfit(int[] prices) {
int[][] dp= new int[prices.length][2];
//此处定义dp, 0代表当天买入股票持有的最大现金, 1表示当天不买股票所持有的最大现金
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1;i<prices.length;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[prices.length-1][1];
}
}