Leetcode 135-分发糖果

1)所有人分1个candy

2)从左往右查看,若满足左规则,令 candy[i] =candy[i - 1] + 1

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

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;

    }
}
相关推荐
草莓熊Lotso13 分钟前
【C++】--函数参数传递:传值与传引用的深度解析
c语言·开发语言·c++·其他·算法
不知名。。。。。。。。19 分钟前
算法 ----- 链式
算法
网易独家音乐人Mike Zhou22 分钟前
【Python】圆柱体内部3D点云仿真及ply文件生成,圆形3D点云检测及拟合算法
stm32·单片机·mcu·物联网·算法·点云·iot
scx201310041 小时前
20250822 组题总结
c++·算法
智驱力人工智能1 小时前
智慧工厂烟雾检测:全场景覆盖与精准防控
人工智能·算法·安全·智慧城市·烟雾检测·明火检测·安全生产
浩少7023 小时前
LeetCode-17day:贪心算法
算法·leetcode·贪心算法
weixin_516875654 小时前
力扣 30 天 JavaScript 挑战 第37天 第九题笔记 知识点: 剩余参数,拓展运算符
javascript·笔记·leetcode
mashanshui7 小时前
Https之(二)TLS的DH密钥协商算法
算法·https·tls·dh·ecdhe
wearegogog12310 小时前
MATLAB的脉搏信号分析预处理
算法·matlab
fs哆哆10 小时前
在VB.net中一维数组,与VBA有什么区别
java·开发语言·数据结构·算法·.net