leetcode中的股票问题(4)
第四题还是有点难的,特别是在连续完成前3题后,思路可能就顿时局限了,主要参考别人的实现,我这里做一些分析。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
原题
Say you have an array for which the
ith
element is the price of a given stock on day
i
.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
翻译:和前一题基本一样,只是从最多2手交易改成了最多
问题分析
这里我的直觉就是用动态规划来解决这个问题,但是具体怎么做呢?
很容易想到的就是维护变量
profit(i,j)
,这里
i
和
profit(i,j)=Max(profit(i−1,j),profitAt(i,j))
其中
profitAt(i,j)
表示,在第i天一定要发生交易的情况下最多做j手交易的最大收益(有点拗口,吼吼吼),因为这样才能对
profit(i,j)
做一个合理的划分。
而
profitAt(i,j)
呢?怎么递推呢?
我们说
profitAt(i,j)=Max(profit(i−1,j−1)+Max(0,diff),profitAt(i−1,j)+diff)
,其中
diff=price(i)−price(i−1)
怎么理解呢,同样是要做一个划分,既然第i天必定有交易(必定有卖出行为),那我对这一手的买进时间做这样划分:买进时间
>=i−1
或者
<i−1
<script type="math/tex" id="MathJax-Element-14">
>=i−1
的情况,在
i−1
天之前就完成
j−1
手交易,而最后一次买卖的收益是
Max(0,diff)
;对于
<i−1
<script type="math/tex" id="MathJax-Element-19">
profitAt(i−1,j)+diff)
来递推,直接加上
diff
的原因是将原本在第
i−1
天卖掉的股票移到第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”操作相关的几个问题~