股票系列问题
建议六道题目按顺序一起看,层层递进,一次解决六道题目
1. 问题
给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 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 。
2. 解析
与上一题 买卖股票的最佳时机 III 解法相同,解析也一样
区别在于,这里的交易次数为k,那么不能像上一题那样写出来交易次数为0,1,2的情况
仍然利用遍历所有情况的思想,将交易次数为0到k的所有情况遍历出来
class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length==0) return 0;
if(k>prices.length/2) return maxProfit(prices.length/2, prices); //最多进行prices.length/2次交易
int profit[][][] = new int[prices.length][k+1][2];
for(int i=0; i<prices.length; i++){
profit[i][0][0] = 0;
}
for(int i=0; i<=k; i++){
profit[0][i][0] = 0;
profit[0][i][1] = -prices[0];
}
for(int i = 1; i<prices.length; i++){
for(int j = 1; j<=k; j++){ //买入算一次交易,卖出不算
profit[i][j][0] = Math.max(profit[i-1][j][0], profit[i-1][j][1]+prices[i]);
profit[i][j][1] = Math.max(profit[i-1][j][1], profit[i-1][j-1][0]-prices[i]);
}
}
return profit[prices.length-1][k][0];
}
}
