Test case [1, 2, 2] needs 5 candies, but the expecting is 4, why?

the left one can have one candy.
his neighbor 2 has higher rank and should have more candies. So the middle child should have 2 candies.
the rightmost child has not higher rank, so there is no need for him to have more candies that anybody else. He can have 1 candies.
So the rightmost and the left most children get 1 and the middle child get 2 candies. A total of 4 candies would be enough