LeetCode题目188. 买卖股票的最佳时机 IV
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例1
输入: [2,4,1], k = 2
输出: 2
解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例2
输入: [3,2,6,5,0,3], k = 2
输出: 7
解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
解题思路
此题为
LeetCode121. 买卖股票的最佳时机
LeetCode123. 买卖股票的最佳时机 III 的扩展。
核心在于对2*k和prices.length的大小判断。当2k>len时,退化为LeetCode122,用贪心算法进行求解;否则退化为次数不超过k次的LeetCode123
完整代码
public int maxProfit(int k, int[] prices) {
if(k<=0||prices==null||prices.length==0)
return 0;
int len=prices.length;
if(k*2>len)//退化为普通的股票问题,用贪心算法即可求解
{
int maxProfit=0;
for (int i = 1; i <len ; i++) {
if(prices[i]>prices[i-1])
maxProfit+=prices[i]-prices[i-1];
}
return maxProfit;
}
int[] buy=new int[len];
int[] sell=new int[len];
Arrays.fill(buy,Integer.MIN_VALUE);
for(int curprice:prices)
for (int i = 1; i <=k; i++) {//k次股票交易
buy[i]=Math.max(buy[i],sell[i-1]-curprice);
sell[i]=Math.max(sell[i],buy[i]+curprice);
}
return sell[k];
}
更多LeetCode题目及答案解析见GitHub: https://github.com/on-the-roads/LeetCode
剑指offer题目及答案解析:https://github.com/on-the-roads/SwordToOffer