A solution from my classmate. We could use profit[0][i] to record the maximum profit from 0 to i and profit[1][i] to record the maximum profit from j to end. So it's a dynamic problem, which could be solved in O(n) time.
class Solution {
public:
int maxProfit(vector &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int i,j,res=0,buy,sell;
vector profit[2];;
if(prices.size()==0) return 0;
else{
buy=prices[0];
profit[0].push_back(0);
for(i=1;i
profit[0][i-1])
profit[0].push_back(prices[i]-buy);
else
profit[0].push_back(profit[0][i-1]);
}
}
sell=prices[prices.size()-1];
profit[1].push_back(0);
for(i=prices.size()-2;i>=0;i--){
if( prices[i]>sell ){
profit[1].push_back( profit[1][profit[1].size()-1] );
sell=prices[i];
}
else{
if( sell-prices[i]>profit[1][profit[1].size()-1] )
profit[1].push_back(sell-prices[i]);
else
profit[1].push_back(profit[1][profit[1].size()-1]);
}
}
for(i=0;ires )
res=profit[0][i]+profit[1][profit[0].size()-1-i];
}
}
return res;
}
};