一、题目描述
- 给定一个整数数组
prices
,它的第i
个元素prices[i]
是一支给定的股票在第i
天的价格。 - 设计一个算法来计算你所能获取的最大利润。你最多可以完成
k
笔交易。 - 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例:
输入 | 输出 | 解释 |
---|---|---|
k = 2, prices = [2,4,1] | 2 | 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4 - 2 = 2 。 |
k = 2, prices = [3,2,6,5,0,3] | 7 | 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6 - 2 = 4 。随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3 - 0 = 3 。 |
提示:
- 0 < = k < = 100 0 <= k <= 100 0<=k<=100
- 0 < = p r i c e s . l e n g t h < = 1000 0 <= prices.length <= 1000 0<=prices.length<=1000
- 0 < = p r i c e s [ i ] < = 1000 0 <= prices[i] <= 1000 0<=prices[i]<=1000
二、求解思路:动态规划
- 沿用 123 - 买卖股票的最佳时机 III 的动态规划思路。
- 单独把
k = 0
的情况拎出来,是因为dp[n_idx][0][0]
恒等于0
是特殊情况。
C++代码
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if(n == 0) {
return 0;
}
int dp[n][2][k+1];
for(int k_idx = 0; k_idx < k+1; k_idx++) {
dp[0][0][k_idx] = 0; dp[0][1][k_idx] = -prices[0];
}
for(int n_idx = 1;n_idx < n; n_idx++) {
dp[n_idx][0][0] = 0;
dp[n_idx][1][0] = max(dp[n_idx-1][0][0] - prices[n_idx], dp[n_idx-1][1][0]);
for(int k_idx = 1; k_idx < k+1; k_idx++) {
dp[n_idx][0][k_idx] = max(dp[n_idx-1][0][k_idx], dp[n_idx-1][1][k_idx-1] + prices[n_idx]);
dp[n_idx][1][k_idx] = max(dp[n_idx-1][0][k_idx] - prices[n_idx], dp[n_idx-1][1][k_idx]);
}
}
return dp[n-1][0][k];
}
};
Python3代码
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
if(n == 0):
return 0
dp = [ [[0]*(k+1), [0]*(k+1)] for i in range(n) ]
for k_idx in range(k+1):
dp[0][0][k_idx] = 0
dp[0][1][k_idx] = -prices[0]
for n_idx in range(1,n):
dp[n_idx][0][0] = 0
dp[n_idx][1][0] = max(dp[n_idx-1][0][0] - prices[n_idx], dp[n_idx-1][1][0])
for k_idx in range(1,k+1):
dp[n_idx][0][k_idx] = max(dp[n_idx-1][0][k_idx], dp[n_idx-1][1][k_idx-1] + prices[n_idx])
dp[n_idx][1][k_idx] = max(dp[n_idx-1][0][k_idx] - prices[n_idx], dp[n_idx-1][1][k_idx])
return dp[n-1][0][k]
Java代码
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if(n == 0) {
return 0;
}
int[][][] dp = new int[n][2][k+1];
for(int k_idx = 0; k_idx < k+1; k_idx++) {
dp[0][0][k_idx] = 0; dp[0][1][k_idx] = -prices[0];
}
for(int n_idx = 1;n_idx < n; n_idx++) {
dp[n_idx][0][0] = 0;
dp[n_idx][1][0] = Math.max(dp[n_idx-1][0][0] - prices[n_idx], dp[n_idx-1][1][0]);
for(int k_idx = 1; k_idx < k+1; k_idx++) {
dp[n_idx][0][k_idx] = Math.max(dp[n_idx-1][0][k_idx], dp[n_idx-1][1][k_idx-1] + prices[n_idx]);
dp[n_idx][1][k_idx] = Math.max(dp[n_idx-1][0][k_idx] - prices[n_idx], dp[n_idx-1][1][k_idx]);
}
}
return dp[n-1][0][k];
}
}
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( n ) O(n) O(n)。
三、参考文章
[1] https://blog.csdn.net/qq_40430360/article/details/124760973