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).
key points: 1. divide to two parts. get the sum of two parts. each part can use the same approach from Sell Stock I.
time complexity O(n^2).
Problems. can not pass large test set cause of exceeding time limit. (maybe more efficient algorithm exists.)
class Solution {
public:
int partialMax(vector<int> &prices, int start, int end) {
if( start >= end) return 0;
int maxPrice = 0;
int minIndex = start;
for( int i=start+1; i<=end; i++) {
if( prices[i] - prices[minIndex] > maxPrice) {
maxPrice = prices[i] - prices[minIndex];
}
if( prices[i] < prices[minIndex]) {
minIndex = i;
}
}
return maxPrice;
}
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sz = prices.size();
if( sz < 2 ) return 0;
if(sz<3) {
return prices[1] - prices[0] > 0 ? prices[1]-prices[0] : 0;
}
int max=INT_MIN;
for(int i=1; i<sz-1; i++) {
int temp = partialMax(prices, 0, i) + partialMax(prices, i, sz-1);
if(temp > max) max = temp;
}
return max;
}
};
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
int sz = prices.length;
if(sz<=1) return 0;
int[] dp1 = new int[sz];
int[] dp2 = new int[sz];
int min = prices[0];
int max = prices[sz-1];
int profit = 0;
for(int i=1; i<sz; i++) {
dp1[i] = Math.max( profit, prices[i]-min);
min = Math.min( prices[i], min);
}
profit = 0;
for( int i=sz-2; i>=0; i--) {
dp2[i] = Math.max( profit, max - prices[i] );
max = Math.max( prices[i], max);
}
int rel=0;
for( int i=0; i<sz; i++) {
rel = Math.max(rel, dp1[i]+dp2[i]);
}
return rel;
}
};
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
int sz = prices.length;
//check input;
if(sz<2) return 0;
int[] d1 = new int[sz];
int[] d2 = new int[sz];
int min=prices[0];
int maxprofit = 0;
d1[0] = 0;
for(int i=1; i<sz; i++) {
if(prices[i]<min) {
min = prices[i];
} else if( prices[i]-min > maxprofit) {
maxprofit = prices[i] - min;
}
d1[i] = maxprofit;
}
int max=prices[sz-1];
maxprofit = 0;
d2[sz-1] = 0;
for(int i=sz-2; i>=0; i--) {
if(prices[i]>max) {
max = prices[i];
}
if( max - prices[i] > maxprofit) {
maxprofit = max - prices[i];
}
d2[i] = maxprofit;
}
maxprofit = 0;
for(int i=0; i<sz; i++) {
if(d1[i] + d2[i] > maxprofit) {
maxprofit = d1[i] + d2[i];
}
}
return maxprofit;
}
}