122. Best Time to Buy and Sell Stock II

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int maxProfit(vector<int>& prices) 
12     {
13         int sz=prices.size();
14         if(sz<2)
15             return 0;
16         int sum=0;
17         for(int i=1;i<sz;i++)
18         {
19             int cur=prices[i]-prices[i-1];
20             if(cur>0)
21                 sum+=cur;
22         }
23         return sum;
24     }
25 };

可以多次买卖的话,就可以利用累加效应,只要后面相邻值大于当前值,就可以获利,将差值作为最大获利值的一部分累加起来。最后结果即为最大获利值。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9057740.html