题解:
根据题目要求,最多进行两次买卖股票,而且手中不能有2只股票,就是不能连续两次买入操作。
所以,两次交易必须是分布在2各区间内,也就是动作为:买入卖出,买入卖出。
进而,我们可以划分为2个区间[0,i]和[i,len-1],i可以取0~len-1。
那么两次买卖的最大利润为:在两个区间的最大利益和的最大利润。
一次划分的最大利益为:Profit[i] = MaxProfit(区间[0,i]) + MaxProfit(区间[i,len-1]);
最终的最大利润为:MaxProfit(Profit[0], Profit[1], Profit[2], ... , Profit[len-1])。\
参考:http://www.cnblogs.com/springfor/p/3877068.html
public class Solution {public int maxProfit(int[] prices) {if (prices == null || prices.length <= 1) {return 0;}int[] left = new int[prices.length];int[] right = new int[prices.length];
//DP from left to rightint min = prices[0];for (int i = 1; i < prices.length; i++) {min = prices[i] < min ? prices[i] : min;left[i] = Math.max(left[i - 1], prices[i] - min);}
//DP from right to leftint max = prices[prices.length - 1];for (int i = prices.length - 2; i >= 0; i--) {max = prices[i] > max ? prices[i] : max;right[i] = Math.max(max - prices[i], right[i+1]);}int profit = 0;for (int i = 0; i < prices.length; i++) {profit = Math.max(left[i] + right[i], profit);}return profit;} }