问题描述:
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.
思路:
这道题目的标签里有动态规划,所以我一开始是用动态规划的方法做的。用m[i][j]记录i到j的最大利润。提交的时候显示超时了,显然 O(n2) 的复杂度不行了。
后来观察代码发现,计算两次交易最大利润的时候只用到了m[n][n]中的第一行和最后一行,那么显然可以优化了。
再分析问题可以发现,要计算两次交易的最大利润,可以把价格数组划分成两部分,prices[0…k]和prices[k…n-1],分别计算出两部分的最大利润,相加即可,复杂度为 O(n) 。
0到k的最大利润,从前往后计算,需要记录0到k之间的最小价格;k到n-1的最大利润,从后往前计算,需要记录k到n-1之间的最大价格。
代码:
public int maxProfit(int[] prices) {
if (prices.length == 0 || prices == null) {
return 0;
}
int n = prices.length;
int[] min_price_from_start = new int[n];
int[] max_price_to_end = new int[n];
int[] max_profit_from_start = new int[n];
int[] max_profit_to_end = new int[n];
min_price_from_start[0] = prices[0];
max_price_to_end[n-1] = prices[n-1];
max_profit_from_start[0] = 0;
max_profit_to_end[n-1] = 0;
for (int i = 1; i < n; i++) {
min_price_from_start[i] = Math.min(prices[i], min_price_from_start[i-1]);
max_profit_from_start[i] = Math.max(prices[i] - min_price_from_start[i], max_profit_from_start[i-1]);
}
for (int i = n-2; i >= 0; i--) {
max_price_to_end[i] = Math.max(prices[i], max_price_to_end[i+1]);
max_profit_to_end[i] = Math.max(max_price_to_end[i] - prices[i], max_profit_to_end[i+1]);
}
int max_1 = max_profit_from_start[n-1];
int max_2 = 0;
for (int i = 1; i < n-1; i++) {
max_2 = Math.max(max_2, max_profit_from_start[i] + max_profit_to_end[i]);
}
return Math.max(max_1, max_2);
}