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).
public class S123 { //分成两段求最大子数组, //forward[i]表示1~i这段最大子数组和,backward[i]表示从prices.length-1~1这段最大子数组和 //最后找出forward[i]与backward[i+1]和最大值即所求 //求forward[i]与backward[i]的方法与053kadane's algorithm类似 public int maxProfit(int[] prices) { if(prices.length<2) return 0; int result =0; int sum = 0; int []forward = new int[prices.length]; forward[0] = Integer.MIN_VALUE; int []backward = new int[prices.length+1]; backward[prices.length] = Integer.MIN_VALUE; for(int i = prices.length-1;i>0;i--){ prices[i] = prices[i]-prices[i-1]; if(sum<0) sum = 0; sum+=prices[i]; backward[i] = sum>backward[i+1]?sum:backward[i+1]; } sum = 0; for(int i = 1;i<prices.length;i++){ if(sum<0) sum = 0; sum+=prices[i]; forward[i] = sum>forward[i-1]?sum:forward[i-1]; if(forward[i]>0&&backward[i+1]>0){ result = forward[i]+backward[i+1]>result?forward[i]+backward[i+1]:result; }else{ result = forward[i]>result?forward[i]:result; result = backward[i+1]>result?backward[i+1]:result; } } return result; } }