123. Best Time to Buy and Sell Stock III
我又闻到了dp的味道
题干:
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 two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
解释:
买卖股票的最终版本。要求最多完成两次交易,求最大收益,没有手续费。
思考:
类似这种问题肯定是用dp来解决,因为每一天都是一个stage,买,或者不买.但是具体的算法还是没想出来,看了答案才知道原来是要用一个local和一个global,两个都是二维数组,分别是局部最大值和全局最大值。 这里我们先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。下面我们来看递推式,全局的比较简单, global[i][j]=max(local[i][j],global[i-1][j]), 也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。对于局部变量的维护,递推式是 local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff), 也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。
答案:
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int[] local = new int[3];
int[] global = new int[3];
for(int i=0;i<prices.length-1;i++)
{
int diff = prices[i+1]-prices[i];
for(int j=2;j>=1;j--)
{
local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
global[j] = Math.max(local[j],global[j]);
}
}
return global[2];
}
答案补充:
实际上这个题是非常类似于上个题的是否最后一个字符被使用的思路的。 anyway如果是我遇到这个题大概还是写不出来,所以也无所谓啦。。。