[leetcode-135]Candy(java)

问题描述:
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?

分析:这道题自己由简单越想越复杂。首先,我们把所有的case分开看。如果把rating画成图,那么只有两种case:
1. 递增:num[i] = num[i-1]+1;
2. 递减:num[i] = num[i+1] +1;

会不会引用一个未定义的值?不会,因为我们可以对所有num先初始化为1。
既然有了这种规律,我们就可以来两次遍历:
从左到右:这样将把所有递增的点确定值。
从右到左:所有递减的点确定了值。
转折点呢?取二者的最大值。

代码如下:436ms

public class Solution {
     public int candy(int[] ratings) {
        int length = ratings.length;
        if(length<=0)
            return 0;
        int[] nums = new int[length];
        nums[0] = 1;
        for(int i = 1;i1;
            if(ratings[i]>ratings[i-1])
                nums[i] = nums[i-1]+1;
        }
        for(int i = nums.length-2;i>=0;i--){
            if(ratings[i]>ratings[i+1])
                nums[i] = Math.max(nums[i],nums[i+1]+1);
        }
        int count = 0;
        for(int i = 0;ireturn count;
    }
}

你可能感兴趣的:(leetcode)