最大子数组问题
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0||prices.size()==1) return 0;
for(auto i=prices.begin();i!=prices.end()-1;++i)
{
*i=*(i+1)-*i;
}
prices.pop_back();
int cur=0,max=0,maxpos;
for(auto i=prices.begin();i!=prices.end();++i)
{
cur+=*i;
if(cur>max)
{
max=cur;
maxpos=i-prices.begin();
}
if(cur<0) cur=0;
}
if(max==0) return 0;
return max;
}
};
优化后的代码:
int maxProfit(vector<int>& prices) {
int last = 0, profit = 0;
for (int i = 0; i < (int)prices.size() - 1; ++i) {
last = max(0, last + prices[i + 1] - prices[i]);
profit = max(profit, last);
}
return profit;
}