LeetCode-135 Distributing Candy-Greedy

Insert picture description here
Requirements subject is at least one candy each child, for a child of the left child or right child, a high score more than the candy must
traversing from left to right, you can achieve a high score to the right of the child is always more than candy left the child
with Li, traversing from right to left, you can achieve a high score on the left to the right of the child's extra child candy
from the top two will achieve a score greater than for a single child left excess candy left, scores greater than the right candy is greater than the right, and the least In the case of sweets, the optimal distribution is achieved for each child. This is so-called greedy

When going from left to right, the initial value is 1, direct right=left+1
but when going from right to left, left=right+1 may not be true, because our requirement is greater than, but right +1<left original The value may affect the operation from left to right, so if the original value is large, the original value will be continued

class Solution {
    
    
    public int candy(int[] ratings) {
    
    
         int size=ratings.length;
        //当只有一个孩子,一个糖果就够
        if(size<2){
    
    
            return size;
        }

        int num[]=new int[size];
        //因为每人至少一个糖果,设置初值每人一个糖果
        for(int i=0;i<size;i++){
    
    
            num[i]=1;
        }

        //从左到右遍历,只要右边评分大于等于左边
        //就让右边的糖果大于左边糖果个数(大最小的个数即1)
        //num和ratings对应每个孩子
        for(int i=0;i<size-1;i++){
    
    
            if(ratings[i+1]>ratings[i]){
    
    
                num[i+1]=num[i]+1;
            }
        }
        //从右到左遍历,只要左边糖果评分大于右边
        //左边=max(右边+1,num[i]原值)
        //num和ratings对应每个孩子
        for(int i=size-1;i>0;i--){
    
    
            if(ratings[i]<ratings[i-1]){
    
    
                num[i-1]=Math.max(num[i-1],num[i]+1);
            }
        }
        int sum=0;
        for (int i:num
             ) {
    
    
            sum+=i;
        }
        return sum;
    }
}

Guess you like

Origin blog.csdn.net/WA_MC/article/details/115256959