↓Skip to main content
  1. LeetCode/

LeetCode 135: Candy

·2 mins· ·
LeetCode Hard Greedy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2025-08-05

  • Submissions: Runtime Error ×3 → Accepted ×2 → Time Limit Exceeded → Accepted

Approach
#

Each child’s condition involves both neighbors, so handle each side separately (Greedy Template 3):

  • left[i]: left side only. Higher than the left neighbor means left[i - 1] + 1, otherwise 1.
  • right[i]: right side only, computed right to left.
  • Each child gets max(left[i], right[i]).

Both are necessary lower bounds: the increasing run on the left forces a minimum, and so does the run on the right, so the larger is the least possible.

My Attempts
#

I started with divide and conquer: find the highest-rated child in a range, recurse on both halves, then give that child one more than any lower-rated neighbor.

VersionProblem
First two REsratings.index(max(ratings[left:right])) searched the whole array for the maximum, possibly finding a position outside the range. [2, 2] gave 3 candies (answer 2) and [4, 1, 2] recursed forever
Third RESearched within the slice, but recursed right on max_index < n - 1; with the maximum at the range’s right end it recursed into an empty range and max() failed on an empty sequence, e.g. [0, 2, 4]
Two ACsChanged to max_index < right - 1, but took 6.5 s: on increasing ratings each level shrinks by one, O(n²)
TLEReplaced the built-in max / index with a hand-written loop; still O(n²), and the Python loop is slower

Solution
#

class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        left = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                left[i] = left[i - 1] + 1
        right = [1] * n
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                right[i] = right[i + 1] + 1
        return sum(max(a, b) for a, b in zip(left, right))

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • When recursing on a subrange, search for positions within that subrange, not the whole array.
  • Recursion bounds must use the subrange’s right end, not the array’s.
  • Splitting at the maximum each level degrades to O(n²) on monotonic input.

Interview Explanation
#

The condition involves both sides, so I make two passes: left to right, a child rated higher than the left neighbor gets one more than them; right to left, the same against the right neighbor. Each child takes the larger, since both are necessary lower bounds. Time O(n).

Related

LeetCode 3638: Maximum Balanced Shipments
·2 mins
LeetCode Medium Dynamic-Programming Greedy Monotonic-Stack Array
LeetCode 3638 note: greedily cut a segment as soon as a value below its maximum appears; until then the segment is non-decreasing, so its maximum is the previous value
LeetCode 3627: Maximum Median Sum of Subsequences of Size 3
·2 mins
LeetCode Medium Math Greedy Sorting Game-Theory Array
LeetCode 3627 note: after sorting, each group takes the two largest and the smallest, with the second largest as the median; the answer takes every other value from the end, n / 3 of them
LeetCode 927: Three Equal Parts
·3 mins
LeetCode Hard Math Array
LeetCode 927 note: every part has the same number of 1s, so count them; the third part always runs to the end of the array, fixing what each part must match, then check the parts do not overlap
LeetCode 952: Largest Component Size by Common Factor
·2 mins
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
LeetCode 952 note: sharing a factor ⇔ sharing a prime factor; factor each number and union indices with the same prime factor using Union-Find, with no pairwise GCDs
LeetCode 3487: Maximum Unique Subarray Sum After Deletion
·2 mins
LeetCode Easy Greedy Hash-Table Array
LeetCode 3487 note: free deletion means picking distinct values; take every non-negative one, or only the maximum when all are negative
LeetCode 3074: Apple Redistribution into Boxes
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 3074 note: apples can be split freely, so take boxes from the largest capacity until the total fits every apple