leetcode-贪心-122. 买卖股票的最佳时机 II

 

 

这题可以用动态规划。

题目中指出:注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。但是没有没有提及 同一天不能发生两笔交易

因此可以用贪心算法。因为贪心算法中同一天先卖出后买入。

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

 

posted @ 2021-08-09 16:24  三一一一317  阅读(25)  评论(0)    收藏  举报