candy

题目描述

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?

思路

思路1:
找出最小值,分成两段,根据左右的情况填这个最小值,然后这两段带边界值递归。
思路2:
左右各扫一遍,遇到不符合要求的加1

代码

public class Solution {
    public int candy(int[] ratings) {
        if(ratings==null||ratings.length==0){
            return 0;
        }
        if(ratings.length==1){
            return 1;
        }
        int[] nums = new int[ratings.length];
        for (int i = 0; i < nums.length; i++) {
            nums[i]=1;
        }
        //scan from left to right
        for (int i = 1; i < ratings.length; i++) {
            if(ratings[i]>ratings[i-1]){
                nums[i]=nums[i-1]+1;
            }
        }
        //scan from right to left
        for (int i = ratings.length-2; i >= 0; i--) {
            if(ratings[i]>ratings[i+1]&&nums[i]<=nums[i+1]){
                nums[i]=nums[i+1]+1;
            }
        }
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            result+=nums[i];
        }
        return result;
    }
}