LeetCode-Best time to buy and sell stock II

很简单,稍微观察一下就可以得出规律:每次买入之后在最高的时候卖出,

只需用low和high来记录买入、卖出的价格,遇到更高价格的时候更新high,否则卖出,

然后同时更新low和high。结束之后最后一次的收入=high - low不要忘了加进去!

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (prices.empty()) {
 7             return 0;
 8         }
 9         int low = prices[0];
10         int high = prices[0];
11         int sum = 0;
12         for (size_t i = 1; i < prices.size(); ++i) {
13             if (prices[i] > high) {
14                 high = prices[i];
15             }
16             else {
17                 sum += (high - low);
18                 low = prices[i];
19                 high = prices[i];
20             }
21         }
22         sum += (high - low);
23         return sum;
24     }
25 };
原文地址:https://www.cnblogs.com/chasuner/p/besttimeII.html