假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。
样例
给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6
注意
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
if(null == prices || prices.length < 2)return 0;
int[] profitLeft = new int[prices.length];
int[] profitRight = new int[prices.length];
int minPrice = prices[0];
for(int i = 1; i < prices.length; i++) {
profitLeft[i] = Math.max(profitLeft[i - 1], prices[i] - minPrice);
minPrice = Math.min(minPrice, prices[i]);
}
int maxPrice = prices[prices.length - 1];
for(int i = prices.length - 2; i >= 0; i--) {
profitRight[i] = Math.max(profitRight[i + 1], maxPrice - prices[i]);
maxPrice = Math.max(maxPrice, prices[i]);
}
int result = 0;
for(int i = 0; i < prices.length; i++) {
result = Math.max(result, profitLeft[i] + profitRight[i]);
}
return result;
}
};