Leetcode 135-分发糖果

1)所有人分1个candy

2)从左往右查看,若满足左规则,令 candyi =candyi - 1 + 1

3)从右往左查看,若满足右规则,令 candyj =Math.max(candyj + 1 + 1,candyj),取最大值是为了在满足右规则的时候不破坏左规则

bash 复制代码
class Solution {
    public int candy(int[] ratings) {
        if(ratings.length==0) return 0;
        int candy[] =new int[ratings.length];
        int total=0;
        candy[0]=1;
        //从左向右遍历数组使其满足左规则
        for(int i=1;i<ratings.length;i++){
            candy[i]=1;
            if(ratings[i]>ratings[i-1]){
                candy[i]=candy[i-1]+1;
            }
        }
        //从右向左遍历数组使其满足左规则
        for(int i=ratings.length-2;i>=0;i--){
            if(ratings[i]>ratings[i+1]){
                candy[i]=Math.max(candy[i+1]+1,candy[i]);
            }
        }
         //遍历获得糖果总数
        for(int i=0;i<ratings.length;i++){
            total+=candy[i];
        }
        return total;

    }
}
相关推荐
hold?fish:palm24 分钟前
45 二叉树的右视图
开发语言·c++·算法
粤鼎恒业1 小时前
惠州工厂电子料回收厂家推荐:从交接单反推筛选标准
大数据·数据库·算法·硬件架构·硬件工程·pcb工艺·材料工程
小爷毛毛(卓寿杰)1 小时前
【Agent 意图识别】输出协议、评估与置信度
人工智能·算法·大模型·prompt·大语言模型·agent
优质酸酸乳1 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光1 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控
旋生万物2 小时前
Agent System Prompt 注入螺旋公理:让 AI 推理不跑偏的可复制模板(附完整 Prompt)
人工智能·算法
深圳雨林凯AI2 小时前
图案裂变的空间关系原理:元素放大为何必然挤压负空间,以及三个可调变量|雨林凯AI技术拆解
人工智能·算法
tellmewhoisi2 小时前
机器学习:聚类算法
算法·机器学习·聚类
yi0113 小时前
LeetCode 134 加油站:从 双循环暴力 演变到 贪心
linux·算法·leetcode
sogw-三叶草️3 小时前
LeetCode 989. 数组形式的整数加法
数据结构·算法