![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 def candy(ratings): 2 result=[1 for i in range(len(ratings))] 3 for i in range(len(ratings)-1): 4 if ratings[i]>ratings[i+1] and result[i]<=result[i+1]: 5 result[i]+=result[i+1]-result[i]+1 6 if ratings[i]<ratings[i+1] and result[i]>=result[i+1]: 7 result[i+1]+=result[i]-result[i+1]+1 8 for j in range(len(ratings)-1,0,-1): 9 if ratings[j]>ratings[j-1] and result[j]<=result[j-1]: 10 result[j]+=result[j-1]-result[j]+1 11 if ratings[j]<ratings[j-1] and result[j]>=result[j-1]: 12 result[j-1] += result[j ] - result[j-1] + 1 13 print(result) 14 return sum(result)