lintcode-medium-Best Time to Buy and Sell Stock III
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.
Given an example [4,4,6,1,1,4,2,5]
, return 6
.
这题和I差不多,用两个数组l2r和r2l记录:第i天前最多做一次交易的最大获利,以及第i天之后最多做一次交易的最大获利。最后结果是两个数组对应的数的和的最大值
class Solution { /** * @param prices: Given an integer array * @return: Maximum profit */ public int maxProfit(int[] prices) { // write your code here if(prices == null || prices.length < 2) return 0; int[] l2r = new int[prices.length]; int[] r2l = new int[prices.length]; l2r[0] = 0; r2l[prices.length - 1] = 0; int min = prices[0]; int max = prices[prices.length - 1]; for(int i = 1; i < prices.length; i++){ if(prices[i] < min) min = prices[i]; l2r[i] = Math.max(l2r[i - 1], prices[i] - min); } for(int i = prices.length - 2; i >= 0; i--){ if(prices[i] > max) max = prices[i]; r2l[i] = Math.max(r2l[i + 1], max - prices[i]); } int result = 0; for(int i = 0; i < prices.length; i++){ if(l2r[i] + r2l[i] > result) result = l2r[i] + r2l[i]; } return result; } };