HardNo. 0135

Candy — LeetCode 135 Python Solution

Pattern
Greedy
Topics
Greedy, Array
On a study list
Top Interview 150
Reading time
2 min

The problem

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

Example

Input
ratings = [1,0,2]
Output
5
Explanation
You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Python solution

PythonSolution
class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        left = [1] * n
        right = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                left[i] = left[i - 1] + 1
        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 log n)
Space · auxiliary
O(1) to O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 135. Candy is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0134Gas StationMedium
0011Container With Most WaterMedium
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0330Patching ArrayHard
0334Increasing Triplet SubsequenceMedium

Frequently asked questions

How hard is LeetCode 135. Candy?

LeetCode 135. Candy is rated Hard on LeetCode.

What topics does LeetCode 135. Candy cover?

LeetCode 135. Candy is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.