imashutosh51

Candy

Mar 23rd, 2026
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. #We will have to assing 1 to all as the first value as It must have atleast 1 candy.
  2. #Suppose we traversed from the left then we can manage the increasing numbers streak by increasing 1 in the previous value and keeping as 1 for the same numbers streak as there is no instructions for the same numbers but when it comes to decreasing, we might get stuck so we will have to do the same form the right side traversal also.
  3. class Solution:
  4.     def candy(self, ratings: List[int]) -> int:
  5.         ans=[1]*len(ratings)
  6.         for i in range(1,len(ratings)):
  7.             if ratings[i-1]<ratings[i]:
  8.                 ans[i]=ans[i-1]+1
  9.  
  10.         for i in range(len(ratings)-2,-1,-1):
  11.             if ratings[i+1]<ratings[i] and ans[i+1]>=ans[i]:
  12.                 ans[i]=ans[i+1]+1
  13.  
  14.         return sum(ans)
  15.  
  16.        
Advertisement
Add Comment
Please, Sign In to add comment