Skip to content

135: Candy #229

@poorvikaa08

Description

@poorvikaa08

Problem Number

135

Problem Title

Candy (Leetcode Hard)

LeetCode Link

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

Contribution Checklist

  • I have written the Approach section.
  • I have written the Intuition section.
  • I have included a working C++ solution.
  • I will raise a PR and ensure the filename follows the convention [Number]. [Problem Title].cpp.

Approach

  1. Initialize a candies vector of size n with all values as 1 (each child gets at least 1 candy).
  2. Traverse the ratings from left to right, and if a child has a higher rating than the previous child, increment their candy count.
  3. Traverse from right to left, and if a child has a higher rating than the next child, update their candy count to max(current, next+1).
  4. Sum up all candies and return the total.

Data structures used:
vector for storing candies assigned to each child.

Time Complexity:
O(n), because we traverse the ratings array twice.

Space Complexity:
O(n), due to the candies vector.

Intuition

  • Each child must get at least one candy.
  • By scanning left-to-right and right-to-left, we ensure both neighbor conditions (higher rating → more candies) are satisfied.
  • Using max prevents overwriting a higher candy count already assigned.

Solution in C++

class Solution {
public:
    int candy(vector<int>& ratings, int cnt = 0) {
        int n = ratings.size();
        vector<int> candies(n, 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 - 1; i > 0; i--) {
            if (ratings[i - 1] > ratings[i])
                candies[i - 1] = max(candies[i] + 1, candies[i - 1]);
            cnt += candies[i - 1];
        }
        return cnt + candies[n - 1];
    }
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions