您的位置:首页 > 其它

LeetCode 123 Best Time to Buy and Sell Stock III

2016-04-12 00:54 489 查看
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).

front[i] 表示区间[0,i]的最大利润,back[i] 表示区间[i,n-1]的最大利润,n表示总天数。最大利润就是 max{ front[i]+back[i] }
0<=i<=n-1.

public int maxProfit3(int[] prices) {
if (prices.length == 0) return 0;
int minbuy = prices[0], profit = 0;
int[] front = new int[prices.length];
front[0] = 0;
int[] back = new int[prices.length];
back[prices.length - 1] = 0;
for (int i = 1; i < prices.length; i++) {
minbuy = Math.min(prices[i], minbuy);
front[i] = Math.max(front[i - 1], prices[i] - minbuy);
}
for (int i = prices.length - 2, maxSell = prices[prices.length - 1]; i > 0; i--) {
maxSell = Math.max(prices[i], maxSell);
back[i] = Math.max(back[i - 1], maxSell - prices[i]);
}
for (int i = 0; i <prices.length ; i++) {
profit = Math.max(front[i]+back[i],profit);
}
return profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: