135. Candy | LeetCode | Top Interview 150 | 코딩 질문

발행: (2025년 12월 18일 오전 08:13 GMT+9)
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 크기의 도시를 나타냅니다. 또한 2차원 배열 buildings가 주어지는데, 여기서 buildings_i = x, y는 …을 나타냅니다.