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

题目链接

解题思路1:因为交易次数不受限,如果可以把所有的上坡全部收集到,一定是利益最大化的。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty() || prices.size() <= 1) return 0;

        int ans = 0;
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] > prices[i-1]) {  // 卖出有利可图
                ans += (prices[i] - prices[i-1]);
            }
        }

        return ans;
    }
};

 

解题思路2:动态规划

 

解题思路3:贪心

 

posted @ 2021-03-31 17:33  洗盏更酌  Views(28)  Comments(0Edit  收藏  举报