121.买卖股票的最佳时机

在这里插入图片描述

最大子数组问题

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;
}
发布了90 篇原创文章 · 获赞 7 · 访问量 2163

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103354621
今日推荐