23贪心算法

分发饼干

cpp 复制代码
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        int i=0,j=0;
        int count=0;
        sort(s.begin(),s.end());
        sort(g.begin(),g.end());
        while(i<g.size()&&j<s.size()){
            if(g[i]<=s[j]){
                i++;
                j++;
                count++;
            }else{
                j++;
            }
        }
        return count;
    }
};

摆动序列

cpp 复制代码
class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int count=1;
        int prev=nums[0];
        bool neg=0;
        int start=1;
        for(int i=1;i<nums.size();i++){
            if(i==start){
                if(prev==nums[i]){
                    start++;
                    continue;
                }else{
                    neg=nums[i]>prev?1:0;
                    prev=nums[i];
                    count++;
                    continue;
                }
                
            }
            if(neg){
                if(nums[i]<prev){
                    neg=0;
                    prev=nums[i];
                    count++;
                }else{
                    prev=nums[i];
                }
            }else{
                if(nums[i]>prev){
                    neg=1;
                    prev=nums[i];
                    count++;
                }else{
                    prev=nums[i];
                }
            }
        }
        return count;
    }
};

最大子序列和

cpp 复制代码
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res=-__INT32_MAX__;
        int max=res;
        for(int num:nums){
            if(res<0)res=num;
            else{
                res+=num;
            }
            if(res>max)max=res;
        }
        return max;
    }
};
相关推荐
不会就选b2 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_35 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z5 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧6 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背6 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝6 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD7 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl8 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
木子算法9 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪