您的位置:首页 > 其它

【LeetCode】Candy

2013-12-30 13:11 260 查看
Candy

Total Accepted: 4149 Total Submissions: 26052 My Submissions

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?

【解题思路】

应该是上升序列和下降序列的合集吧。

声明一个数组candyNum[],表示下标为i的人所拥有的糖果数目。

初始化时每个人所拥有的糖果数目为1。

int len = ratings.length

从开头上升过程。

从0开始循环到len-2。

如果ratings[i] < ratings[i+1],那么candyNum[i+1] = candyNum[i]+1;

从结尾上升过程。

从len-2循环到0。

如果ratings[i+1] > ratings[i],并且candyNum[i+1] <= candyNum[i],那么candyNum[i+1] <= candyNum[i]

其实就是这样一个过程。



最后循环candNum,累加就是最后结果。

Java AC

public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0){
            return 0;
        }
        int len = ratings.length;
        int candyNum[] = new int[len];
        for(int i = 0; i < len; i++){
            candyNum[i] = 1;
        }
        for(int i = 1; i < len; i++){
            if(ratings[i] > ratings[i-1]){
                candyNum[i] = candyNum[i-1]+1;
            }
        }
        for(int i = len-2; i >= 0; i--){
            if(ratings[i] > ratings[i+1] && candyNum[i] <= candyNum[i+1]){
                candyNum[i] = candyNum[i+1]+1;
            }
        }
        int allCandy = 0;
        for(int i = 0; i < len; i++){
            allCandy += candyNum[i];
        }
        return allCandy;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: