今天的題目為123.Best Time to Buy and Sell Stock III,今天是最難的版本,今天是給定一個整數陣列prices,其中prices[i]表示第i天某支股票的價格,請找出能夠獲得的最大利潤而最多可以完成兩次交易,不能同時進行多筆交易。
以下為程式碼:
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int n = prices.length;
int[] leftProfit = new int[n];
int[] rightProfit = new int[n];
int minPrice = prices[0];
for (int i = 1; i < n; i++) {
minPrice = Math.min(minPrice, prices[i]);
leftProfit[i] = Math.max(leftProfit[i - 1], prices[i] - minPrice);
}
int maxPrice = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
maxPrice = Math.max(maxPrice, prices[i]);
rightProfit[i] = Math.max(rightProfit[i + 1], maxPrice - prices[i]);
}
int maxTotalProfit = 0;
for (int i = 0; i < n; i++) {
maxTotalProfit = Math.max(maxTotalProfit, leftProfit[i] + rightProfit[i]);
}
return maxTotalProfit;
}
}
今天的是最最最難的一題,需要很多不同的轉換。