135. Candy
problem description
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy. Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
algorithm thought
使用一个数组表示给所有小朋友分配的糖果,开始所有的小朋友都是1个。
一个小朋友等级比旁边的高的话,他的糖果必须必旁边的多。旁边有两个,首先我们让所有小孩向左看时,满足条件,然后让所有小孩往右看时满足条件,最后就能有结果。
code
algorithm analysis
算法两次遍历数组,最后时间复杂度O(n).
Last updated