目录结构
1.题目
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
动态规划。
dp[i][0]
表示第 i 天不持有股票的最大收益,- 它取【第i-1天不持有股票的最大收益】与【第i-1天持有股票的最大收益在第i天卖出股票】的较大值,
- 即dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1]
表示第 i 天持有股票的最大收益,- 它取【第i-1天持有股票的最大收益】与【第i-2天不持有股票的最大收益在第i天买入股票】的较大值,
- 即dp[i][1] = Math.max(dp[i - 1][1], dp[i - 2][0] - prices[i])。
public class Solution309 {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int len = prices.length;
int[][] dp = new int[len][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[1][0] = Math.max(dp[0][0], dp[0][1] + prices[1]);
dp[1][1] = Math.max(dp[0][1], dp[0][0] - prices[1]);
for (int i = 2; i < len; 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 - 2][0] - prices[i]);
}
return dp[len - 1][0];
}
}
- 时间复杂度:
- 空间复杂度:
- 注意到在动态规划状态转移方程中,
- 对于当前i只有用到dp[i-1][0]、dp[i-1][1]和dp[i-2][0],
- 其他数据无需存储,故可对空间进行进一步优化。
public class Solution309 {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int len = prices.length;
int pre_pre_0, pre_pre_1, pre_0, pre_1;
pre_pre_0 = 0;
pre_pre_1 = -prices[0];
pre_0 = Math.max(pre_pre_0, pre_pre_1 + prices[1]);
pre_1 = Math.max(pre_pre_1, pre_pre_0 - prices[1]);
for (int i = 2; i < len; i++) {
int tmp_0 = Math.max(pre_0, pre_1 + prices[i]);
int tmp_1 = Math.max(pre_1, pre_pre_0 - prices[i]);
pre_pre_0 = pre_0;
pre_0 = tmp_0;
pre_1 = tmp_1;
}
return pre_0;
}
}
- 时间复杂度:
- 空间复杂度: