【代码随想录算法训练营第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

相关推荐
CoovallyAIHub20 分钟前
标注成本骤降,DINOv3炸裂发布!冻结 backbone 即拿即用,性能对标SOTA
深度学习·算法·计算机视觉
BB学长20 分钟前
流固耦合|01流固耦合分类
人工智能·算法
汤永红34 分钟前
week3-[分支嵌套]方阵
c++·算法·信睡奥赛
广州智造37 分钟前
EPLAN教程:流体工程
开发语言·人工智能·python·算法·软件工程·软件构建
闪电麦坤951 小时前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤951 小时前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
球king1 小时前
数据结构中邻接矩阵中的无向图和有向图
数据结构
自信的小螺丝钉1 小时前
Leetcode 343. 整数拆分 动态规划
算法·leetcode·动态规划
Q741_1471 小时前
C++ 力扣 438.找到字符串中所有字母异位词 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
Fine姐1 小时前
数据挖掘3.6~3.10 支持向量机—— 核化SVM
算法·支持向量机·数据挖掘