MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / candy

Method candy

python/0135-candy.py:2–21  ·  view source on GitHub ↗
(self, ratings: List[int])

Source from the content-addressed store, hash-verified

1class Solution:
2 def candy(self, ratings: List[int]) -> int:
3 n = len(ratings)
4 # Initialize with one candy becuase each child must have at least one candy.
5 candies = [1] * n
6
7 # Iterate from left to right
8 for i in range(1, n):
9 # Check if current rating is greater than left neighbor
10 if ratings[i] > ratings[i - 1]:
11 # Rating is higher so deserves more candy than left neighbor
12 candies[i] = candies[i - 1] + 1
13
14 # Iterate from right to left
15 for i in range(n - 2, -1, -1):
16 # Check if current rating is greater than right neighbor
17 if ratings[i] > ratings[i + 1]:
18 # Take max to check if the value is already greater than its right neighbor + 1.
19 candies[i] = max(candies[i], candies[i + 1] + 1)
20
21 return sum(candies)

Callers

nothing calls this directly

Calls 2

maxFunction · 0.50
sumFunction · 0.50

Tested by

no test coverage detected