leetcode 122 买卖股票的最佳时机II

 

贪心算法:如果今天买明天能够盈利,那就今天买入明天卖出;对于这个问题来讲是具有最优子结构性质的

分情况:

1)当len<1;不会赚钱,return 0;

2)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //贪心算法
        int res=0;
        int len=prices.size();
        if(len<1) return 0;
        for(int i=1;i<len;i++){
            if(prices[i]-prices[i-1]>0)
                res+=prices[i]-prices[i-1];
        }
        return res;
    }
};

 

posted @ 2019-04-09 15:05  Joel_Wang  阅读(207)  评论(0编辑  收藏  举报