Simple solution with one pass using O(1) space
To use two variables  \'up\' and \'down\' to count the steps of continuous up and down respectively, and a \'peak\' representing the peak before going down. In 
To use two variables  \'up\' and \'down\' to count the steps of continuous up and down respectively, and a \'peak\' representing the peak before going down. In the below example:\n```\n[0, 1, 20, 9, 8, 7]\n```\nScan from left to right, first child is given 1 candy;\nthe second child is given 2 candies,  and up=1;\nthe third child is given 3 candies,  and up=2; peak=2;\nthe fourth child is given 1 candy,  and down=1; and third child still has 3 candies since peak=2;\nthe fifth child is given 1 candy,  and down=2; and the previous child needs 1 more candy now but the third child no need more;\nthe sixth child is given 1 candy,  and down=3; and both the fifth and fourth child needs 1 more candy now, and the peak, the third child need 1 more as well.\n```\n        public int Candy(int[] ratings) {\n            if (ratings.Length == 0) return 0;\n            int ret = 1;\n            int up = 0, down = 0, peak = 0;\n            for (int i = 1; i < ratings.Length; i++) {\n                if (ratings[i - 1] < ratings[i]) {\n                    peak = ++up;\n                    down = 0;\n                    ret += 1 + up;\n                } else if (ratings[i - 1] == ratings[i])  {\n                    peak = up = down = 0;\n                    ret += 1;\n                } else {\n                    up = 0;\n                    down++;\n                    ret += 1 + down + (peak >= down ? -1 : 0);\n                }\n            }\n\n            return ret;\n        }\n```\n
[]