码迷,mamicode.com
首页 > 其他好文 > 详细

(LeetCode 135) Candy

时间:2015-05-06 21:12:47      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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个孩子站成一排,给每个人设定一个权重(已知)。按照如下的规则分配糖果: (1)每个孩子至少分得一颗糖果 (2)权重较高的孩子,会比他的邻居获得更多的糖果。

问:总共最少需要多少颗糖果?请分析算法思路,以及算法的时间,空间复杂度是多少。

 

思路:

假设每个孩子分到的糖果数组为A[N],初始化为{1},因为每个人至少分到一颗糖。

方法一:

1、与前面的邻居比较,前向遍历权重数组ratings,如果ratings[i]>ratings[i-1],则A[i]=A[i-1]+1;

2、与后面的邻居比较,后向遍历权重数组ratings,如果ratings[i]>ratings[i+1]且A[i]<A[i+1]+1,则更新A,A[i]=A[i+1]+1;

3、对A求和即为最少需要的糖果。

时间复杂度:O(n)

空间复杂度:O(n)

方法二:

设数组A1,保存前向遍历的结果,设数组A2,保存后向遍历的结果;

1、与前面的邻居比较,前向遍历权重数组ratings,如果ratings[i]>ratings[i-1],则A1[i]=A1[i-1]+1;

2、与后面的邻居比较,后向遍历权重数组ratings,如果ratings[i]>ratings[i+1],则A2[i]=A2[i+1]+1;

3、每个孩子分到的糖果比前后邻居多,为A1、A2的较大者,即A[i]=max(A1[i],A2[i]);

4、对A求和即为最少需要的糖果。

时间复杂度:O(n)

空间复杂度:O(n)

代码:

class Solution {
public:
    int candy(vector<int>& ratings) {
        int n=ratings.size();
        int sum;
        
        vector<int> nums(n,1);
        for(int i=1;i<n;i++){
            if(ratings[i]>ratings[i-1])
                nums[i]=nums[i-1]+1;
        }
        
        sum=nums[n-1];
        for(int i=n-2;i>=0;i--){
            if(ratings[i]>ratings[i+1] && nums[i]<nums[i+1]+1)
                nums[i]=nums[i+1]+1;
            sum+=nums[i];
        }
        
        return sum;
    }
};
class Solution {
public:
    int candy(vector<int>& ratings) {
        int n=ratings.size();
        int sum=0;
        
        vector<int> nums(n,1);
        vector<int> for_nums(n,1);
        vector<int> back_nums(n,1);
        
        for(int i=1;i<n;i++){
            if(ratings[i]>ratings[i-1])
                for_nums[i]=for_nums[i-1]+1;
        }
        
        for(int i=n-2;i>=0;i--){
            if(ratings[i]>ratings[i+1])
                back_nums[i]=back_nums[i+1]+1;
        }
        
        for(int i=0;i<n;i++){
            nums[i]=max(for_nums[i],back_nums[i]);
            sum+=nums[i];
        }
        
        return sum;
    }
};

(LeetCode 135) Candy

标签:

原文地址:http://www.cnblogs.com/AndyJee/p/4483043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!