31代码随想录训练营day31|贪心算法part01

1、分发饼干

分发饼干

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int index = s.size() - 1;
        int count = 0;
        for (int i = g.size() - 1; i >= 0; i--) {	// 胃
            if (index >= 0 && s[index] >= g[i]) {	// 饼干
                count++;
                index--;
            }
        }
        return count;
    }
};

2、摆动序列

摆动序列

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int predif = 0;
        int curdif = 0;
        int count = 1;
        if (nums.size() <= 1) return nums.size();
        for (int i = 0; i < nums.size() - 1; i++) {
            curdif = nums[i + 1] - nums[i];
            if ((predif <= 0 && curdif > 0) || (predif >= 0 && curdif < 0)) {
                count++;
                predif = curdif;
            }
        }
        return count;
    }
};

3、最大子数组和

最大子数组和

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int count = 0;
        int result = INT_MIN;
        for (int i = 0; i < nums.size(); i++) {
            count += nums[i];
            if (count > result) {
                result = count;
            }
            if (count < 0) {
                count = 0;
            }
        }
        return result;
    }
};

你可能感兴趣的:(代码随想录训练营,贪心算法,算法,c++,leetcode)