屡明白就行了,就是找小的,然后找大的,没找到这样一个组合就进行一次交易,把利润加到结果里,继续找。假设小数是5大数是9,对于之间出现的按序的数比如6,7,8不影响结果,因此直接略过,但对于不安续出现的比如5,8,7,9这样的话因为可以进行两次交易,这样利润会更大。
int maxProfit(vector<int> &prices) {
if(prices.size()==0||prices.size()==1)
return 0;
int sumprofit = 0;
int buypoint=0,sellpoint=0;
while(buypoint<prices.size())
{
while(buypoint<prices.size()-1&&prices[buypoint]>=prices[buypoint+1])
buypoint++;
sellpoint = buypoint + 1;
if(sellpoint==prices.size())
break;
while(sellpoint<prices.size()-1&&prices[sellpoint]<=prices[sellpoint+1])
sellpoint++;
if(prices[sellpoint]>prices[buypoint])
sumprofit += (prices[sellpoint]-prices[buypoint]);
buypoint = sellpoint + 1;
}
return sumprofit;
}