暴力超时版本
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <=0){
return 0;
}
int n = prices.size();
int dp1 = 0;
for (int i = 0; i < n; i++)
{
dp1 = max(dp1,
maxRange(prices, 0, i) + maxRange(prices, i, n));
}
return dp1;
}
int maxRange(vector<int>& prices, int start, int end){
int dp = 0;
int minP = 0;
minP = prices[start];
for (int i = start; i < end; i++)
{
dp = max(dp , prices[i] - minP);
if(prices[i] < minP){
minP = prices[i];
}
}
return dp;
}
};
优化版本
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <=0){
return 0;
}
int n = prices.size();
vector<int> min_f(n+1, 0);
vector<int> max_p(n+1, 0);
vector<int> max_b(n+1, 0);
min_f[0] = prices[0];
for(int i = 1; i<prices.size(); i++){
min_f[i] = min(prices[i], min_f[i - 1]);
}
max_b[prices.size() - 1] = prices[prices.size() - 1];
max_p[n-1] = 0;
for(int i = prices.size() - 2; i>=0; i--){
max_b[i] = max(prices[i], max_b[i + 1]);
max_p[i] = max(max_b[i] - prices[i], max_p[i+1]);
}
int dp1 = 0;
for (int i = 0; i < n -1; i++)
{
dp1 = max(dp1, prices[i] - min_f[i] + max_p[i]);
}
dp1 = max(dp1, prices[n-1]- min_f[n-1] + max_p[n-1]);
return dp1;
}
};