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).
给一个一维数组,代表每天股票价格,找出交易两次最大的获利选择
例如
Input: [7, 1, 5, 3, 6, 4]
最大为7,即【1,5】=4,【3,6】=3
用dp1[i]记录maxprofit[0,i],
用dp2[i]记录maxprofit[i,len-1]
输出就是max(dp1[i]+dp2[i]), i=0~n-1
public static int maxProfit(int[] prices) {
int len = prices.length;
if(len<=1)return 0;
int max=0;
int dp1[] = new int[len];
int curmin= prices[0];
for(int i=1;i<len;i++){
max = max < prices[i] - curmin ? prices[i] - curmin : max;
curmin = prices[i] < curmin ? prices[i] : curmin;
dp1[i] = max;
}
int curmax= prices[len-1];
max=0;
int dp2[] = new int[len];
for(int i=len-1;i>=0;i--){
max = max < curmax-prices[i] ? curmax-prices[i] : max;
curmax = prices[i] > curmax ? prices[i] : curmax;
dp2[i] = max;
}
max=0;
for(int i=len-1;i>0;i--){
max = max < dp1[i]+dp2[i] ? dp1[i]+dp2[i] : max;
}
return max;
}
本文介绍了一种求解在一维数组中进行至多两次股票买卖以获得最大利润的算法。该算法通过动态规划实现,使用两个数组dp1和dp2分别记录从前向后和从后向前的最大利润,最终输出所有可能的利润组合中的最大值。
591

被折叠的 条评论
为什么被折叠?



