leetcode-135. Candy

原创 2016年08月29日 21:43:29

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?

题意解析:

题目大概就是说有一群小孩,每个小孩有个得分,现在要给小孩子发糖,得分高的小孩应该比他旁边得分低的小孩得到的糖果要多,求问最少需要多少糖果。

最少的情况其实很简单,就是最低的人是1,比他高一点就+1,这道题难度是hard,可是我感觉只有easy,因为思路是直的,完全没拐弯,代码如下:

public class Solution {
    public int candy(int[] ratings) {
        if(ratings.length == 1){
            return 1;
        }
        int[] candys = new int[ratings.length];
        candys[0] = 1;
        for(int i = 1; i < ratings.length; i++){
            if(ratings[i] > ratings[i - 1]){
                candys[i] = candys[i - 1] + 1;
            }else{
                candys[i] = 1;
            }
        }
        for(int i = ratings.length - 2; i >= 0; i--){
            if(ratings[i] > ratings[i + 1] && candys[i] <= candys[i + 1]){
                candys[i] = candys[i + 1] + 1;
            }
        }
        int sum = 0;
        for(int x : candys){
            sum += x;
        }
        return sum;
    }
}

复杂度O(n),其实就是正向一次,反向一次。正向的时候默认是1,如果右边比左边高,就在原来的基础上+1,否则都是1。反向的时候,如果左边比右边高,而且左边糖果没有右边多,那左边的糖果就在右边的基础上+1。


结果也是在最快的那一组里面。别的算法我也想不到。不知道为什么有的人时间会那么慢。


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

[leetcode] 135.Candy

题目: There are N children standing in a line. Each child is assigned a rating value.You are giving c...

Leetcode. 135 Candy(Hard)

**Problem** There are N children standing in a line. Each child is assigned a rating value.  You...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

LeetCode 135. Candy (O(n)时间 O(n)和O(1)空间的两种实现)

贪心算法,从局部最优推广成全局最优。 这里介绍O(n)时间 O(n)和O(1)空间的两种实现方法。

LeetCode Algorithms 135. Candy 题解

There are N children standing in a line. Each child is assigned a rating value. You are givi...

LeetCode135 Candy

详细见:leetcode.com/problems/candy Java Solution: github package leetcode; /* * There are N...

LeetCode题解–135. Candy

链接LeetCode题目:https://leetcode.com/problems/candy/难度:Hard题目 There are N children standing in a line...

[LeetCode] 135. Candy java

/**135. Candy * @param ratings * @return */ public int candy(int[] ratings) { ...

LeetCode-135. Candy (JAVA)根据等级分糖果

LeetCode-135. Candy (JAVA)根据等级分糖果

[leetcode] 135. Candy

There are N children standing in a line. Each child is assigned a rating value. You are giving can...

Leetcode (135) Candy

题目 There are N children standing in a line. Each child is assigned a rating value. You are giv...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)