12.25 2014
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) {
int day=prices.size();
if(day<2) return 0;
int Max=0;
int Max1=0;
int Max2=0;
int lowest=prices[0];
for(int i=0;i<day;i++){
Max1=helper(prices,0,i);
Max2=helper(prices,i+1,day-1);
Max=max(Max1+Max2,Max);
}
return Max;
}
int helper(vector<int> &prices, int start, int end){
int profit=0;
int lowest=prices[start];
for(int i=start;i<=end;i++){
profit=max(prices[i]-lowest,profit);
lowest=min(lowest,prices[i]);
}
return profit;
}
};
做法一:拆成两段,对两段分别求最大和,加起来的和取最大值即为答案。但是会出现超时。
class Solution {
public:
int maxProfit(vector<int> &prices) {
int day=prices.size();
if(day<2) return 0;
vector<int> v(day,0);
vector<int> p(day,0);
for(int i=1, valley=prices[0];i<day;i++){
valley=min(valley,prices[i]);
v[i]=max(v[i-1],prices[i]-valley);
}
for(int i=day-2, peak=prices[day-1];i>=0;i--){
peak=max(peak,prices[i]);
p[i]=max(p[i],peak-prices[i]);
}
int profit=0;
for(int i=0;i<day;i++)
profit=max(profit,v[i]+p[i]);
return profit;
}
};
做法二:
稍微有些不同,主要是在代码上的区别,空间和时间上的tradeoff,把各种可能先算一遍存在vector内然后再进行求最大值。