#135

Candy

Hard
ArrayGreedyGreedy AlgorithmArray Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses two passes through the ratings array to ensure that the candy distribution meets the requirements efficiently. This method is more efficient because it only requires linear time while ensuring that all conditions are met.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an array 'candies' of the same length as 'ratings', with each element set to 1.
  2. 2Step 2: Traverse the 'ratings' array from left to right. If a child has a higher rating than the previous child, give them one more candy than the previous child.
  3. 3Step 3: Traverse the 'ratings' array from right to left. If a child has a higher rating than the next child, ensure they have more candies than the next child, adjusting if necessary.
  4. 4Step 4: Sum all the values in the 'candies' array to get the total number of candies needed.
solution.py10 lines
1def candy(ratings):
2    n = len(ratings)
3    candies = [1] * n
4    for i in range(1, n):
5        if ratings[i] > ratings[i - 1]:
6            candies[i] = candies[i - 1] + 1
7    for i in range(n - 2, -1, -1):
8        if ratings[i] > ratings[i + 1]:
9            candies[i] = max(candies[i], candies[i + 1] + 1)
10    return sum(candies)

Complexity note: The time complexity is O(n) because we traverse the ratings array twice. The space complexity is O(n) due to the additional candies array used to store the candy distribution.

  • 1Each child must have at least one candy, which is the base case.
  • 2The relationship between ratings and candies is directional; we need to check both left and right neighbors.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.