[One Question of the Day] Likou 135: Distribute Candy

Title description ( portal )

The teacher wants to distribute candies to the children. N children stand in a straight line, and the teacher will rate each child in advance based on their performance.

You need to help the teacher distribute candies to these children according to the following requirements:

Each child is allocated at least 1 candy.
The child with a higher score must get more candies than the children next to him.
So how many candies should the teacher prepare?

Example

Example 1:

输入:[1,0,2]
输出:5
解释:你可以分别给这三个孩子分发 212 颗糖果。

Example 2:

输入:[1,2,2]
输出:4
解释:你可以分别给这三个孩子分发 121 颗糖果。
     第三个孩子只得到 1 颗糖果,这已满足上述两个条件。

Ideas

The child with a higher score must get more candies than the children next to him.
According to requirements, we have to consider the sides of each child, so there are two rules. I looked at the solution and felt that the official method was still very clear.
We divide the requirements intoLeft rulewithRight rule
Rating array: rating[n]
left rule statistics candy array: left[n]
right rule statistics candy array: right[n]

Left rule (compared from left to right according to the rating array): when i = 0, left[0] = 1, then handle i> 0, rating[i]> rating[i-1], left[i] = left [i-1] + 1; otherwise left[i] = 1;

Right rule (compare from right to left according to the rating array): when i = n-1, right[n-1] = 1, then handle 0<=i <n-1, rating[i]> rating[i+ 1],right[i] = right[i+1] + 1; otherwise, right[i] = 1; the
Insert picture description here
red line in the figure above is the result after the left rule. The green line is the result after the right rule.
Insert picture description here

Finally, as shown in the figure above, we take the left and right rules, and the maximum value corresponding to each person can ensure that the left and right rules are met at the same time, and the sum is the final result.

Code

public static int candy(int[] ratings) {
    
    
        int[] left = new int[ratings.length];
        for (int i = 0; i < ratings.length; i++) {
    
    
            if(i > 0 && ratings[i] > ratings[i-1]) {
    
    
                left[i] = left[i-1] + 1;
            }else {
    
    
                left[i] = 1;
            }
        }
        int[] right = new int[ratings.length];
        int ret = 0;
        for (int i = ratings.length - 1; i >= 0; i--) {
    
    
            if (i < ratings.length - 1 && ratings[i] > ratings[i + 1]) {
    
    
                right[i] = right[i+1] + 1;
            }
            else {
    
    
                right[i] = 1;
            }
            ret += Math.max(left[i] , right[i]);
        }
        return ret;

    }

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/111666811
Recommended