MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / candies

Function candies

python3/Greedy/candies.py:4–22  ·  view source on GitHub ↗
(ratings: List[int])

Source from the content-addressed store, hash-verified

2
3
4def candies(ratings: List[int]) -> int:
5 n = len(ratings)
6 # Ensure each child starts with 1 candy.
7 candies = [1] * n
8 # First pass: for each child, ensure the child has more candies
9 # than their left-side neighbor if the current child's rating is
10 # higher.
11 for i in range(1, n):
12 if ratings[i] > ratings[i - 1]:
13 candies[i] = candies[i - 1] + 1
14 # Second pass: for each child, ensure the child has more candies
15 # than their right-side neighbor if the current child's rating is
16 # higher.
17 for i in range(n - 2, -1, -1):
18 if ratings[i] > ratings[i + 1]:
19 # If the current child already has more candies than their
20 # right-side neighbor, keep the higher amount.
21 candies[i] = max(candies[i], candies[i + 1] + 1)
22 return sum(candies)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected