121. 买卖股票的最佳时机
思路:动态规划五步曲
- dp[i][0] 表示第i天不持有股票所得最多现金,dp[i][1] 表示第i天持有票所得最多现金。
- dp[i][0]和dp[i][1]都有两种方式可以推导出来,分别是前一天持有股票和前一天不持有股票的情况。
所以递推公式:
- dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1])
- dp[i][1] = max(dp[i - 1][1], -prices[i])
- 初始化dp[0][0] = 0, dp[0][1] = -prices[0]
- 由递推公式可以看出,需要从前向后遍历
- 举例说明
class Solution {
public int maxProfit(int[] prices) {
// dp[i][0] 表示第i天不持有股票所得最多现金,dp[i][1] 表示第i天持有票所得最多现金
int[][] dp = new int[prices.length][2];
// 递推公式 dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1])
// dp[i][1] = max(dp[i - 1][1], -prices[i])
// 初始化
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], prices[i] + dp[i - 1][1]);
dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
}
return dp[prices.length - 1][0];
}
}
122.买卖股票的最佳时机II
思路:和上一题的区别主要体现在递推公式上,主要讲解递推公式,其他步骤与上一题相同。
因为上一题股票只能够买卖一次,所以在第i天持有股票的时候,需要重新计算,不能加上i-1天未持有股票所得的利润。而本题股票可以买卖多次,所以在第i天持有股票的时候,需要加上之前已经得到的利润(即i-1天未持有股票的利润),所以本题递推公式:
- dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1])
- dp[i][1] = Math.max(dp[i - 1][1], -prices[i] + dp[i - 1][0]);
class Solution {
public int maxProfit(int[] prices) {
// dp[i][0] 表示在第i天不持有股票的最大利润
// dp[i][1] 表示在第i天持有股票的最大利润
int[][] dp = new int[prices.length][2];
// 递推公式:dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1])
// dp[i][1] = max(dp[i - 1][1], -prices[i] + dp[i - 1][0])
// 初始化
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], prices[i] + dp[i - 1][1]);
dp[i][1] = Math.max(dp[i - 1][1], -prices[i] + dp[i - 1][0]);
}
return dp[prices.length - 1][0];
}
}