135. Candy | LeetCode | Top Interview 150 | Coding Questions

Published: (December 17, 2025 at 06:13 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

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

leetcode 135

Solution

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

Related posts

Read more »

3531. Count Covered Buildings

Problem Description You are given a positive integer n, representing an n × n city. You are also given a 2D array buildings, where buildingsi = x, y denotes a...