美文网首页
leetcode 122. Best Time to Buy a

leetcode 122. Best Time to Buy a

作者: Terence_F | 来源:发表于2016-07-13 10:22 被阅读18次

Best Time to Buy and Sell Stock II

unlocked question, 所以不贴截图了

This solution is really smart. 当后一个比前一个大的时候,把差值加入result中。 e.g.: {7, 1, 2, 5, 4, 3},7, 1递减,不对result操作。 1,2,5递增,5 - 1 = (2 - 1) + (5 - 2), 把(2 - 1) and (5 - 2)分别加入result。

class Solution {
public:
   int maxProfit(vector<int>& prices) {
       int res = 0;
       for (int i = 1; i < prices.size(); i++)
           res += max(prices[i] - prices[i - 1], 0);
       return res;
   }
};

相关文章

网友评论

      本文标题:leetcode 122. Best Time to Buy a

      本文链接:https://www.haomeiwen.com/subject/rcvsjttx.html