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;

    }
}
相关推荐
不見星空15 分钟前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack26 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx2 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior3 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者3 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价4 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七4 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战4 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode