leetcode中的股票問題(4)
第四題還是有點難的,特別是在連續完成前3題後,思路可能就頓時侷限了,主要參考別人的實現,我這裏做一些分析。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
原題
Say you have an array for which the
Design an algorithm to find the maximum profit. You may complete at most k transactions.
翻譯:和前一題基本一樣,只是從最多2手交易改成了最多
問題分析
這裏我的直覺就是用動態規劃來解決這個問題,但是具體怎麼做呢?
很容易想到的就是維護變量
其中
而
我們說
怎麼理解呢,同樣是要做一個劃分,既然第i天必定有交易(必定有賣出行爲),那我對這一手的買進時間做這樣劃分:買進時間
然後就很簡單了,直接上代碼。
下面的代碼中 global就是profit()函數,而local就是profitAt()函數。
代碼
public int maxProfit(int k, int[] prices) {
if(prices==null || prices.length==0)
return 0;
//如果k>一半天數,問題退化成問題(3)了
if(k > prices.length/2)
{
int sum =0;
for(int i = 0 ; i < prices.length-1 ; i++)
{
int gain = prices[i+1] - prices[i];
if(gain > 0)
sum += gain;
}
return sum;
}
int[][] global=new int[prices.length][k+1];
int[][] local=new int[prices.length][k+1];
for(int i=0;i<prices.length-1;i++)
{
int diff=prices[i+1]-prices[i];
for(int j=0;j<=k-1;j++)
{
local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);
global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);
}
}
return global[prices.length-1][k];
}
接下來我們會去看看在leetcode中和數組以及鏈表的“rotate”操作相關的幾個問題~