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

LeetCode:Candy

时间:2016-05-27 12:05:53      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

Candy




Total Accepted: 52308 Total Submissions: 231427 Difficulty: Hard

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?

Subscribe to see which companies asked this question

Hide Tags
 Greedy



















思路:

1.先给每个小孩分1 个candy;

2.从左往右:如果,左<右,则右边小孩加1颗candy;

2.从右往左:如果,左>右,则左边小孩要比右边的candy多。


java code:

public class Solution {
    public int candy(int[] ratings) {
        
        int len = ratings.length;
        int[] candies = new int[len];
        for(int i=0;i<len;i++) candies[i] = 1;
        
        for(int i=1;i<len;i++) {
            if(ratings[i-1] < ratings[i])
                candies[i] = candies[i-1] + 1;
        }
        
        for(int i=len-1;i>0;i--) {
            if(ratings[i-1] > ratings[i])
                candies[i-1] = Math.max(candies[i-1], candies[i]+1);
        }
        
        int ans = 0;
        for(int candy : candies) {
            ans += candy;
        }
        
        return ans;
    }
}


LeetCode:Candy

标签:

原文地址:http://blog.csdn.net/itismelzp/article/details/51502655

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