leetcode @python 135. Candy

题目链接

https://leetcode.com/problems/candy/

题目原文

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?

题目大意

有n个小孩排成一列,每个小孩有一个value值,现在要给这群小孩分糖果,需要满足下面两个条件:1.每个小孩至少要有一颗糖果 2.value值比较高的小孩的糖果数要比站在他旁边的小孩多

解题思路

1.每个小孩的初始糖果值为1
2.从头开始遍历,保证位于位置i的value值高的小孩肯定比位置i-1的小孩糖果数要多
3.从后往前遍历,保证位于位置i-1的value值高的小孩肯定比位置i的小孩糖果数要多
4.求和

代码

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        n = len(ratings)
        candy = [1 for i in range(n)]
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                candy[i] = candy[i-1] + 1

        for i in range(n - 1, 0, -1):
            if ratings[i] < ratings[i - 1] and candy[i] >= candy[i - 1]:
                candy[i - 1] = candy[i] + 1

        return sum(candy)
posted @ 2016-04-08 10:33  slurm  阅读(351)  评论(0编辑  收藏  举报