Candy (Python)
kitt
posted @ 2014年2月11日 23:36
in LeetCode
, 1657 阅读
neighbors就是指左边一个和右边一个, 只有比neighbor的rating高的孩子得到的糖才能更多, rating为1, 2, 2时糖数为1, 2, 1。正向扫一遍, 后一个比前一个rating高则后一个的糖数要增加, 再反向扫一遍, 同样处理。
class Solution: # @param ratings, a list of integer # @return an integer def candy(self, ratings): length = len(ratings) candy = [1 for i in xrange(length)] for i in xrange(length - 1): if ratings[i+1] > ratings[i] and candy[i+1] <= candy[i]: candy[i+1] = candy[i] + 1 for i in reversed(xrange(1, length)): if ratings[i-1] > ratings[i] and candy[i-1] <= candy[i]: candy[i-1] = candy[i] + 1 return sum(candy)