fork download
  1. def candy(ratings):
  2. n = len(ratings)
  3. if n == 0:
  4. return 0
  5.  
  6. # Step 1: Initialize candies array
  7. candies = [1] * n
  8.  
  9. # Step 2: Left to right pass
  10. for i in range(1, n):
  11. if ratings[i] > ratings[i - 1]:
  12. candies[i] = candies[i - 1] + 1
  13.  
  14. # Step 3: Right to left pass
  15. for i in range(n - 2, -1, -1):
  16. if ratings[i] > ratings[i + 1]:
  17. candies[i] = max(candies[i], candies[i + 1] + 1)
  18.  
  19. # Step 4: Calculate total candies
  20. return sum(candies)
  21.  
  22. # Example usage:
  23. print(candy([1, 0, 2])) # Output: 5
  24. print(candy([1, 2, 2])) # Output: 4
Success #stdin #stdout 0.09s 14064KB
stdin
2
s r t r d q s
+hor++++++
+and+et++
+usd++e+++
+++a+++r++
+h++++++++
++++++++++
++++++++++
+dp+t+++++
+++hq+++++
++++++++++
3.68977 0.922431
stdout
5
4