------
## 最终结论
```python
def candy(ratings):
    n = len(ratings)
    candies = [1] * n  # Initialize candies array with 1 candy for each child

    # Traverse from left to right
    for i in range(1, n):
        if ratings[i] > ratings[i - 1]:
            candies[i] = candies[i - 1] + 1

    # Traverse from right to left
    for i in range(n - 2, -1, -1):
        if ratings[i] > ratings[i + 1] and candies[i] <= candies[i + 1]:
            candies[i] = candies[i + 1] + 1

    return sum(candies)  # Calculate total candies

# Example usage:
ratings = [1, 0, 2]
print(candy(ratings))  # Output: 5

ratings = [1, 2, 2]
print(candy(ratings))  # Output: 4
```