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

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


一、455.分发饼干

解题代码C++:

cpp 复制代码
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());

        int result = 0;
        int index = s.size() - 1;
        for(int i = g.size() - 1; i >= 0; i --)
            if(index >= 0 && g[i] <= s[index])
            {
                result ++;
                index --;
            }
        
        return result;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0455.分发饼干.html



二、376. 摆动序列

解题代码C++:

cpp 复制代码
class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        if (nums.size() <= 1) return nums.size();
        int curDiff = 0; // 当前一对差值
        int preDiff = 0; // 前一对差值
        int result = 1;  // 记录峰值个数,序列默认序列最右边有一个峰值
        for (int i = 0; i < nums.size() - 1; i++) {
            curDiff = nums[i + 1] - nums[i];
            // 出现峰值
            if ((preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0)) {
                result++;
                preDiff = curDiff; // 注意这里,只在摆动变化的时候更新prediff
            }
        }
        return result;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0376.摆动序列.html



三、53. 最大子序和

解题代码C++:

cpp 复制代码
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = -1e5 - 10;
        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;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0053.最大子序和.html

相关推荐
erzong23134 分钟前
Linux操作系统:线程概念与控制
linux·算法
Nil2081 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
xxwl5851 小时前
区域赛分类题解
c++·笔记·学习·算法
m0_674571971 小时前
力扣 hot 100 python
python·算法·leetcode
青少儿编程课堂2 小时前
蓝桥杯+全国青少年信息素养大赛+电子学会PythonC/C++考级:最长公共子序列LCS解析
c++·python·算法·bfs·信息学竞赛
倚楼听风语3 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
程序员清风3 小时前
双指针与滑动窗口:高效处理连续区间
开发语言·算法
代钦塔拉3 小时前
【C++/Qt 进阶】设计模式系列(2):工厂模式——从游戏角色到披萨店
c++·算法·设计模式
思茂信息3 小时前
电磁仿真学涉及哪些算法?
人工智能·算法·数学建模·matlab·emc·电磁仿真·仿真辐射
糖果豆豆4 小时前
让 AI 自查三遍,它只会把错的说得更像对的——检查的人和被检查的,是同一个
算法·架构