โ† Back to Index

๐Ÿ“š Candy โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Candy problem involves distributing candies to children standing in a line such that:

The goal is to determine the minimum number of candies required to satisfy these conditions.

๐Ÿงฑ Pattern Template

Two-Pass Greedy Algorithm

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int[] candies = new int[n];
        Arrays.fill(candies, 1);

        // Left-to-right pass
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }

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

        // Calculate the total candies
        int totalCandies = 0;
        for (int candy : candies) {
            totalCandies += candy;
        }

        return totalCandies;
    }
}

๐ŸŽฅ Video Explanation

For a detailed explanation, watch this video: Candy Problem Explanation by NeetCode IO

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: ratings = [1,0,2]
Output: 5

Explanation:
- Give 2 candies to the child with a rating of 2.
- Give 1 candy to the child with a rating of 0.
- Give 2 candies to the child with a rating of 1.
- Total candies = 2 + 1 + 2 = 5.

๐Ÿ’ก Pro Tips