0%

Best Time to Buy and Sell Stock III

Question

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 (i.e., you must sell the stock before you buy again).

Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
brute force的优化
双向dp: 一个从左往右计算max profit, 另一个从右往左计算,最后分割,然后取max
*/
public int maxProfit(int[] prices) {
if (prices.length <= 1) {
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 < prices.length; i++) {
if (prices[i] > prices[i-1]) {
left[i] = Math.max(prices[i]-min, left[i-1]);
}else {
left[i] = left[i-1];
min = Math.min(min, prices[i]);
}
}


//注意计算从右往左的时候是记录max
int max = prices[len-1];
right[len-1] = 0;
for (int i = len-2; i >= 0; i--) {
if (prices[i] < prices[i+1]) {
right[i] = Math.max(max-prices[i], right[i+1]);
}else {
right[i] = right[i+1];
max = Math.max(max, prices[i]);
}
}

int res = Math.max(left[len-1], right[0]);
for (int i = 1; i < len-1; i++) {
res = Math.max(left[i]+right[i+1], res);
}
return res;
}