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 (ie, you must sell the stock before you buy again).
最多买卖两次,求最大收益值
1 一开始的思路是这样的:和买卖一次的情形差不多,我只要计算出局部最大和第二大的收益值,最后加一下就可以得到答案。但是这个直觉有漏洞。考虑1,2,4,2,5,7,2,4,9,0,局部最大可以是5(7-2)和7(9-2) 也可以是6(7-1)和7(9-2),我这样的思路是没有办法把这个给区分出来的。
2 理性来说,上述我的想法错误在于我考虑用贪心算法来处理这道题目。可是这道题目适合的做法是动态规划。
3 每次看到两次,两个这样,就考虑区分左右区间,或者上下区间。
4 开两个数组,lmax,rmax,lmax的每个点分别代表此点左边最大收益;rmax代表右边最大收益。最后只要遍历一下就行了。
5 求这两个数组的每个点可以由之前或者之后的点来退出,和买卖一次的情形一样
6 我是参考这个http://blog.youkuaiyun.com/pickless/article/details/12034365 来写出代码的。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1){
return 0;
}
int maxprofit = 0;
int n = prices.length;
int[] lmax = new int[n];
int[] rmax = new int[n];
useme(prices,lmax,rmax,n);
for(int i=0;i<n;i++){
maxprofit = Math.max(maxprofit,lmax[i]+rmax[i]);
}
return maxprofit;
}
public void useme(int[] prices,int[] lmax,int[] rmax,int n){
lmax[0]=0;
int buy = prices[0];
for(int i=1;i<n;i++){
lmax[i]=Math.max(lmax[i-1],prices[i]-buy);
buy = Math.min(buy,prices[i]);
}
rmax[0] = 0;
int sell = prices[n-1];
for(int i = n-2;i>=0;i--){
rmax[i]=Math.max(rmax[i+1],sell-prices[i]);
sell = Math.max(sell,prices[i]);
}
}
}