时间复杂度(O( n2)),感觉效率有些低,等有时间再想想有木有其他方法优化。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<2)return 0;
int max = onemaxProfit(prices,0,prices.size()-1);
for(int i=0;i<prices.size();++i){
int mid_tmp = onemaxProfit(prices,0,i) + onemaxProfit(prices,i,prices.size()-1);
if(mid_tmp>max)max=mid_tmp;
}
return max;
}
int onemaxProfit(vector<int>& prices,int start,int end) {
if(start==end)return 0;
int max = 0;
int value1 = prices[start];
int value2 = prices[start];
for(int i=start+1;i<=end;++i)
if(prices[i]<value1){
value1 = prices[i];
value2 = prices[i];
}else if(prices[i]>value2){
value2 = prices[i];
if(max<value2-value1)
max = value2-value1;
}
return max;
}
};