LeetCode: Best Time to Buy and Sell Stock III 解题报告

时间:2023-02-01 08:49:40

Best Time to Buy and Sell Stock III
Question Solution
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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解答:
1. 从左往右扫描,计算0-i的这个区间的最大利润。方法可以参见股票第一题
2. 从右往左扫描,计算i-len这个区间的最大利润。方法同上。
3. 再从头至尾扫一次,每个节点加上左边和右边的利润。记录最大值。

复制一点别人的讲解:

O(n^2)的算法很容易想到:

找寻一个点j,将原来的price[0..n-1]分割为price[0..j]和price[j..n-1],分别求两段的最大profit。

进行优化:

对于点j+1,求price[0..j+1]的最大profit时,很多工作是重复的,在求price[0..j]的最大profit中已经做过了。

类似于Best Time to Buy and Sell Stock,可以在O(1)的时间从price[0..j]推出price[0..j+1]的最大profit。

但是如何从price[j..n-1]推出price[j+1..n-1]?反过来思考,我们可以用O(1)的时间由price[j+1..n-1]推出price[j..n-1]。

最终算法:

数组l[i]记录了price[0..i]的最大profit,

数组r[i]记录了price[i..n]的最大profit。

已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。

最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。(最后一步可以合并在第二步中)。

REF: http://blog.csdn.net/pickless/article/details/12034365

代码1:

 public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
} int len = prices.length;
int[] left = new int[len];
int[] right = new int[len]; int min = prices[0];
left[0] = 0;
for (int i = 1; i < len; i++) {
min = Math.min(min, prices[i]);
left[i] = Math.max(left[i - 1], prices[i] - min);
} int max = prices[len - 1];
right[len - 1] = 0;
for (int i = len - 2; i >= 0; i--) {
max = Math.max(max, prices[i]);
right[i] = Math.max(right[i + 1], max - prices[i]);
} int rst = 0;
for (int i = 0; i < len; i++) {
rst = Math.max(rst, left[i] + right[i]);
} return rst;
}

代码2:

 public class Solution {
public int maxProfit(int[] prices) {
if (prices == null) {
return 0;
} int ret = 0; int len = prices.length;
int[] leftProfile = new int[len];
int profile = 0; int min = Integer.MAX_VALUE;
for (int i = 0; i < len; i++) {
min = Math.min(min, prices[i]);
profile = Math.max(profile, prices[i] - min);
leftProfile[i] = profile;
} int max = Integer.MIN_VALUE;
profile = 0;
for (int i = len - 1; i >= 0; i--) {
max = Math.max(max, prices[i]);
profile = Math.max(profile, max - prices[i]); // sum the left profit and the right profit.
ret = Math.max(ret, profile + leftProfile[i]);
} return ret;
}
}

DP思路:

 // DP solution:
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
} int ret = 0; int len = prices.length;
int[] leftProfile = new int[len]; int min = prices[0];
leftProfile[0] = 0;
for (int i = 1; i < len; i++) {
min = Math.min(min, prices[i]);
leftProfile[i] = Math.max(leftProfile[i - 1], prices[i] - min);
} int max = Integer.MIN_VALUE;
int profile = 0;
for (int i = len - 1; i >= 0; i--) {
max = Math.max(max, prices[i]);
profile = Math.max(profile, max - prices[i]); // sum the left profit and the right profit.
ret = Math.max(ret, profile + leftProfile[i]);
} return ret;
}

GitHub代码链接