代码随想录27|455.分发饼干,376. 摆动序列,53. 最大子序和

455.分发饼干

链接地址

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

376. 摆动序列

链接地址

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        //峰值个数
        int prediff = 0;
        int curdiff = 0;
        int result = 1;// 设置一个前峰

        for (int i = 0; i < nums.size() - 1; i++) { //nums.size() - 1, 防止i + 1 超过
            curdiff = nums[i + 1] - nums[i];
            if ((prediff <= 0 && curdiff > 0) || (prediff >= 0 && curdiff < 0)) {
                result++;
                prediff = curdiff;
            }
        }
        return result;
    }
};

53. 最大子序和

链接地址

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT32_MIN;
        int count = 0;
        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,算法)