Hard-题目34:135. Candy

转载 2016年05月31日 23:44:51

题目原文:
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个小朋友站成一片,每个小朋友有一个评分。
现在要给这N个小朋友发糖,要求每个小朋友至少一个糖,且相邻两个小朋友中,评分高者要比评分低者得到的糖多。
请问至少需要准备多少颗糖?
题目分析:
使用贪心法来做,首先给每个小朋友一个糖,然后从左到右扫描数组,如果i号小朋友的评分高于i-1号,则给i号小朋友的糖是i-1号小朋友+1,再从右到左扫描数组,如果i号小朋友比i+1号小朋友评分高,则给i号小朋友的糖数是i+1号小朋友和i-1号小朋友的糖数最大值+1.
源码:(language:cpp)

class Solution {
public:
  int candy(vector<int> &ratings)
 {
     int size=ratings.size();
     if(size<=1)
         return size;
     vector<int> num(size,1);
     for (int i = 1; i < size; i++)
     {
         if(ratings[i]>ratings[i-1])
             num[i]=num[i-1]+1;
     }
     for (int i= size-1; i>0 ; i--)
     {
         if(ratings[i-1]>ratings[i])
             num[i-1]=max(num[i]+1,num[i-1]);
     }
     int result=0;
     for (int i = 0; i < size; i++)
     {
         result+=num[i];
        // cout<<num[i]<<" ";
     }
     return result;
 }
};

成绩:
40ms,22.09%,40ms,65.85%
Cmershen的碎碎念:
这道题好像今年alibaba的实习生机试里面考了原题,因此leetcode应重视,如果公司出题人懒,就直接从leetcode里面找题了。

相关文章推荐

Leetcode. 135 Candy(Hard)

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

[Leetcode 135, Hard] Candy

[Leetcode 135, hard] Candy

[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 (O(n)时间 O(n)和O(1)空间的两种实现)

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

171. Excel Sheet Column Number\172. Factorial Trailing Zeroes\134. Gas Station\135. Candy

Excel Sheet Column Number 题目描述 代码实现 Factorial Trailing Zeroes 题目描述 代码实现 Gas Station 题目描述 代码实现 Candy ...

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...

135. Candy

糖果的分配

[LeetCode] 135. Candy java

/**135. Candy * @param ratings * @return */ public int candy(int[] ratings) { ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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