买卖股票的最佳时机 III
题目
假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。
注意事项
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)样例
给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6
题解
动态规划法,以第i天为分界线分别计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。
class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
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];
left[0] = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++)
{
min = Math.min(prices[i], min);
left[i] = Math.max(left[i - 1], prices[i] - min);
}
right[prices.length - 1] = 0;
int max = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--)
{
max = Math.max(prices[i], max);
right[i] = Math.max(right[i + 1], max - prices[i]);
}
int profit = 0;
for (int i = 0; i < prices.length; i++)
{
profit = Math.max(left[i] + right[i], profit);
}
return profit;
}
};
Last Update 2016.10.17