LeetCode 123. 买卖股票的最佳时机 III
题目链接:123. 买卖股票的最佳时机 III - 力扣(LeetCode)
这个道题和121. 买卖股票的最佳时机 I、122. 买卖股票的最佳时机 II很像,是两题的结合。
我们就定义两个数组来实现。
代码:
#python #DP
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
buy1 = buy2 = - prices[0] //卖两次,从定义出发,定义两个阶段的买和卖
sell1 = sell2 = 0
for i in range(1, n):
buy1 = max(buy1, - prices[i])
sell1 = max(sell1, buy1 + prices[i])
buy2 = max(buy2, sell1 - prices[i]) //仔细体会上一题的这个位置
sell2 = max(sell2, buy2 + prices[i])
return sell2
/java
class Solution {
public int maxProfit(int[] prices) {
int[] dp = new int[4];
// 存储两次交易的状态就行了
// dp[0]代表第一次交易的买入
dp[0] = - prices[0];
// dp[1]代表第一次交易的卖出
dp[1] = 0;
// dp[2]代表第二次交易的买入
dp[2] = - prices[0];
// dp[3]代表第二次交易的卖出
dp[3] = 0;
// for(int i = 1; i <= prices.length; i++){
// // 要么保持不变,要么没有就买,有了就卖
// dp[0] = Math.max(dp[0], -prices[i-1]);
// dp[1] = Math.max(dp[1], dp[0]+prices[i-1]);
// // 这已经是第二次交易了,所以得加上前一次交易卖出去的收获
// dp[2] = Math.max(dp[2], dp[1]-prices[i-1]);
// dp[3] = Math.max(dp[3], dp[2]+ prices[i-1]);
// }
for(int i = 0; i < prices.length; i++){
// 要么保持不变,要么没有就买,有了就卖
dp[0] = Math.max(dp[0], - prices[i]);
dp[1] = Math.max(dp[1], dp[0] + prices[i]);
// 这已经是第二次交易了,所以得加上前一次交易卖出去的收获
dp[2] = Math.max(dp[2], dp[1] - prices[i]);
dp[3] = Math.max(dp[3], dp[2] + prices[i]);
}
return dp[3];
}
}
LeetCode 188. 买股票的最佳时机IV
题目链接:188. 买卖股票的最佳时机 IV - 力扣(LeetCode)
这又是上一题的一个进阶版,其实我们上一题考虑了两个,这次直接来一个DP数组就OK。
代码:
#python
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
buy = [-float('inf')] * (k + 1)
sell = [0] * (k + 1) #SELL数组
for price in prices:
for i in range(1, k + 1):
buy[i] = max(buy[i], sell[i - 1] - price)
sell[i] = max(sell[i], buy[i] + price)
return sell[k]
/java
class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length == 0 || k == 0)
return 0;
int dp[] = new int [k * 2 + 1];
for(int i = 1; i < 2 * k + 1; i += 2){
dp[i] = -prices[0];
}
for(int i = 1; i < prices.length; i++){
for(int j = 1; j < 2 * k + 1; j++){
//奇數天購買
if(j % 2 == 1)
dp[j] = Math.max(dp[j], dp[j - 1] - prices[i]);
//偶數天賣出
else
dp[j] = Math.max(dp[j], dp[j - 1] + prices[i]);
}
}
return dp[2 * k];
}
}