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).
Solution:
At first, I tried to use a similar way as Best Time to Buy and Sell Stock I. I used divide and conquer, divide the array into two parts: [0...i][i...n-1], but the recursion process is time-consuming, I got time limit exceed in leetcode online judge.
Think one more step, we use two arrays: l[i] donates max profit for [0...i] and r[i] donates max profit for [i...n-1]. In order to get r[i], we are going to iterate from right to left and record max sell price, since we must sell stock before buy.
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
At first, I tried to use a similar way as Best Time to Buy and Sell Stock I. I used divide and conquer, divide the array into two parts: [0...i][i...n-1], but the recursion process is time-consuming, I got time limit exceed in leetcode online judge.
Think one more step, we use two arrays: l[i] donates max profit for [0...i] and r[i] donates max profit for [i...n-1]. In order to get r[i], we are going to iterate from right to left and record max sell price, since we must sell stock before buy.
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if(n == 0) return 0;
int[] l = new int[n];
int[] r = new int[n];
// max profit from 0 to i;
l[0] = 0;
int minBuy = prices[0];
for(int i = 1; i < n; i++){
// update max profit
l[i] = Math.max(l[i-1], prices[i] - minBuy);
minBuy = Math.min(minBuy, prices[i]);
}
// max profit from i to n;
r[n-1] = 0;
int maxSell = prices[n-1];
for(int i = n-2; i >= 0; i--){
// update max profit
r[i] = Math.max(r[i+1], maxSell - prices[i]);
maxSell = Math.max(maxSell, prices[i]);
}
int result = 0;
for(int i = 0; i < n; i++){
result = Math.max(result, l[i] + r[i]);
}
return result;
}
}
No comments:
Post a Comment