135. Candy[hard]

135. Candy-distribution problem

Problem Description

The teacher wants to distribute candies to the children. There are N children standing 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:

每个孩子至少分配到 1 个糖果。
评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。

So, how many sweets does the teacher need to prepare at least?

Example 1:

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

Example 2:

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

answer

Greedy thinking: First, each child has one candy per person.
Considering the number of assigned candies and the location, the sorting operation cannot be performed.

  • Segmentation sub-problems: consider only one direction at a time
  • Traverse from left to right. If the score on the right is high, assign the number of candies num[i] to the number of candies of the child on the left+1 num[i-1]+1
  • Reverse traversal from right to left When the left is greater than the right, compare at this time max(num[i-1],num[i]+1) Update num[i-1]

Code

class Solution {
    
    
    public int candy(int[] ratings) {
    
    
    //  问题定位:贪心
    // 和身边的人有关 不能改变顺序
    // 最优解:找到老师需要准备的最小糖果数
    //  子问题:两次遍历 先左右,后右左 每次找到应分配的糖果数
    int N = ratings.length;
    int[] num =new int[N];
    int ret=0;
    // 1.每个孩子先都给一个糖
    for(int i=0; i<N ; i++){
    
    
        num[i] = 1 ;
    }
    //2.左到右遍历
    for(int i=1;i<N;i++){
    
    
        if(ratings[i] > ratings[i-1]){
    
    
            num[i] = num[i-1] + 1 ;
        }
    }
    //3.从右向左
    for(int i=N-1;i>0;i--){
    
    
        if(ratings[i] < ratings[i-1]){
    
    
            num[i-1] =Math.max(num[i-1],num[i]+1);
        }
    }
    // 4.计算数目
    for(int i=0;i<N; i++){
    
    
        ret += num[i]; 
    }
    return ret;
    }
}

Guess you like

Origin blog.csdn.net/qq_37747189/article/details/115051609
Recommended