【LeetCode】Candy

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]
其实就是这样一个过程。

【LeetCode】Candy_第1张图片
最后循环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;
    }
}

你可能感兴趣的:(【LeetCode】Candy)