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

发布: (2025年12月18日 GMT+8 07:13)
1 分钟阅读
原文: 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

相关文章

阅读更多 »