标签:des blog http io ar os sp java for
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).
一开始是想定义一个点i,d[i]表示在i点之前卖掉第一次股票所得到的最大利润,这个狂野的想法很明显是要TLE的,最关键的问题是,进行了过多的重复计算,[i…n]和[i+1…n]的最大利润在prices[i+1] < prices[i]的时候是一样的
参考了别人的思路,分别算[0…i]的最大利润和[i…n]的最大利润,很明显[0…i]的最大利润的算法跟之前Stock1的解法是一样的,但是后面[i…n]的解法就更为暴力一点,从后往前扫,遇到最高的就记下来,最大利润就是当前max(highest - prices[i], maxproofit)。
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) {
return 0;
}
// calculating [0...i] max profit
int[] leftMaxProfit = new int[prices.length];
// calculating [i...n] max profit
int[] rightMaxProfit = new int[prices.length];
leftMaxProfit[0] = 0;
for (int i = 1; i < leftMaxProfit.length; i++) {
int changes = prices[i] - prices[i - 1];
leftMaxProfit[i] = leftMaxProfit[i - 1] + changes < 0 ? 0 : leftMaxProfit[i - 1] + changes;
}
rightMaxProfit[0] = 0;
int highest = prices[prices.length - 1];
int maxprofit = Integer.MIN_VALUE;
int ret = 0;
for (int i = rightMaxProfit.length - 1; i >= 1; i--) {
int profit = highest - prices[i];
if (profit > maxprofit) maxprofit = profit;
int finalprofit = maxprofit + leftMaxProfit[i];
if (finalprofit > ret) ret = finalprofit;
if (prices[i] > highest) highest = prices[i];
}
return ret;
}
}标签:des blog http io ar os sp java for
原文地址:http://my.oschina.net/zuoyc/blog/352169