135. Candy | LeetCode | Top Interview 150 | 编程题

发布: (2025年12月18日 GMT+8 07:13)
1 min read
原文: Dev.to

Source: Dev.to

问题链接

https://leetcode.com/problems/candy/

leetcode 135

解法

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int count = 0;
        int[] candies = new int[n];

        // Each child gets at least one candy
        for (int i = 0; i  ratings[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }

        // Right‑to‑left pass
        for (int i = n - 1; i > 0; i--) {
            if (ratings[i - 1] > ratings[i]) {
                candies[i - 1] = Math.max(candies[i] + 1, candies[i - 1]);
            }
            count += candies[i - 1];
        }

        return count + candies[n - 1];
    }
}
Back to Blog

相关文章

阅读更多 »

3531. 统计被覆盖的建筑物

问题描述:给定一个正整数 n,表示一个 n × n 的城市。还给定一个二维数组 buildings,其中 buildings[i] = x, y 表示一个…