代码随想录算法训练营第三十一天|455.分发饼干、376.摆动序列、53.最大子序和

题目链接:455. 分发饼干 - 力扣(Leetcode)

class Solution {
public:
    int findContentChildren(vector& g, vector& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int num = 0;
        for(int i = 0, j = 0; i < g.size() && j < s.size(); i++) {
            while(j < s.size() && g[i] > s[j]) j++;
            if(j == s.size()) return num;
            num++;
            j++;
        }
        return num;
    }
};

题目链接:376. 摆动序列 - 力扣(Leetcode)

class Solution {
public:
    int wiggleMaxLength(vector& nums) {
        if(nums.size() <= 1) return nums.size();
        bool flg = true;
        int state = nums[1] - nums[0];
        int result = 1;
        for(int i = 0; i < nums.size() - 1; i++) {
            if (state != 0) flg = false;
            if(state >= 0) {
                if(nums[i + 1] - nums[i] < 0) {
                    result++;
                    state = nums[i + 1] - nums[i];
                }
            }
            else if(state < 0){
                if(nums[i + 1] - nums[i] > 0) {
                    result++;
                    state = nums[i + 1] - nums[i];
                }
            }
        }
        if(flg) return 1;
        return result;
        
    }
};

题目链接:53. Maximum Subarray - 力扣(Leetcode)

class Solution {
public:
    int maxSubArray(vector& nums) {
        int i = 0, j = 0, sum = 0;
        int result = INT32_MIN;
        while(j < nums.size()) {
            if(sum < 0){
                while(i != j) {
                    sum -= nums[i];
                    i++;
                }
            }
            sum += nums[j];
            if (sum > result) result = sum;
            j++;
        }
        return result;
    }
};

你可能感兴趣的:(代码随想录,leetcode)