# Hard-题目21：123. 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.

dp1因为是正向扫的，所以维护当前子序列的最小值min，可以由dp[i-1]推出dp[i]:
dp[i]=max(dp[i-1],prices[i]-min)，即如果在第i天卖了可以获得更大的收益，则在第i天卖掉，否则与在第i-1天之前卖是一样的。

dp2[i]=max(dp2[i+1],max-prices[i])，道理同上。

public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2)
return 0;
int[] dp1 = new int[prices.length];
int[] dp2 = new int[prices.length];
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < min)
min = prices[i];
dp1[i] = Math.max(dp1[i - 1], prices[i] - min);
}
int max = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
if (prices[i] > max)
max = prices[i];
dp2[i] = Math.max(dp2[i + 1], max - prices[i]);
}
int profit = Math.max(dp1[prices.length-1], dp2[0]);
for (int i = 0; i < prices.length-1; i++) {
if (dp1[i] + dp2[i+1] > profit)
profit = dp1[i] + dp2[i+1];
}
return profit;
}
}

3ms,beats 42.07%,众数2ms,38.19%
Cmershen的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Hard-题目21：123. Best Time to Buy and Sell Stock III 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)