https://leetcode.com/problems/candy/description/?envType=daily-question&envId=2025-06-02
i didnt really get the question but if we have the same rating, the number of candies do not necessarily have to be the same.
For example,
1,2,3,3
means that candy is
1,2,3,1
We can do this via two pass greedy way from left to right and right to left, where if neighbour is greater than current value's raiting, then we take the neighbour's candy +1 and update the current candy as that value.
class Solution:
def candy(self, ratings: List[int]) -> int:
n=len(ratings)
lst = [1 for _ in range(n)]
for i in range(1,n):
if ratings[i]>ratings[i-1]:
if lst[i]<=lst[i-1]:
lst[i]=lst[i-1]+1
elif ratings[i]==ratings[i-1]:
continue
for i in range(n-2,-1,-1):
if ratings[i]>ratings[i+1]:
if lst[i]<=lst[i+1]:
lst[i]=lst[i+1]+1
elif ratings[i]==ratings[i-1]:
continue
return sum(lst)
n time
n space