C++算法学习(贪心算法)

1、目标

不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解 。

2、方法

1、把求解的问题分成若干个子问题
2、对每个子问题求解,得到子问题的局部最优解
3、把子问题的解局部最优解合成原来解问题的一个解

3、例题

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

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int answer = 0;
        if(prices.size() < 2) return 0;
        //每次都找当下可以赚钱的
        for(int i = 0;i < prices.size() - 1;i++){
    
    
            int diff = prices[i+1] - prices[i];
            if(diff > 0) answer += diff;
        }
        return answer;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45743162/article/details/111062215