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)
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty() || prices.size() == 1)
return 0;
int size = prices.size();
vector<int> left(size, 0);
vector<int> right(size, 0);
int result = 0;
int min = prices[0];
int max = prices[size-1];
for(int i = 1; i < size; i++)
{
if(prices[i] < min)
min = prices[i];
left[i] = std::max(left[i-1], prices[i] - min);
}
for(int i = size-2; i >= 0; i--)
{
if(prices[i] > max)
max = prices[i];
right[i] = std::max(right[i+1], max - prices[i]);
}
for(int i = 0; i < size; i++)
{
if(left[i] + right[i] > result)
result = left[i] + right[i];
}
return result;
}
};
Round 2:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0)
return 0;
int *left = (int *)calloc(prices.size(), sizeof(int));
int *right = (int *)calloc(prices.size(), sizeof(int));
int min = prices[0], max = prices[prices.size()-1];
int result = 0;
for(int i = 1; i < prices.size(); i++)
{
int j = prices.size() - i - 1;
min = std::min(prices[i], min);
max = std::max(prices[j], max);
left[i] = std::max(left[i-1], prices[i] - min);
right[j] = std::max(right[j+1], max - prices[j]);
}
for(int i = 0; i < prices.size(); i++)
{
if(left[i] + right[i] > result)
result = left[i] + right[i];
}
return result;
}
};