[LeetCode]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?

解题思路

要保证分数高的孩子分的糖果更多,可以首先初始化每个孩子一颗糖果,然后从左到右遍历一遍,保证正方向上分数高的糖果多,再从右到左遍历一遍,保证反方向上分数高的糖果多(比相邻的多一个)。然后计算总和即可。

具体实现

class Solution {
public:
    int candy(vector<int> &ratings) {
        int len = ratings.size();
        if(len <= 1){
            return len;
        }
        int sum = 0;//糖果总数
        vector<int> candyNum(len,1);//初始化每个孩子分一个糖果
        //从左到右遍历,保证正方向等级越高的糖果数越多
        for(int i = 1; i <= len; i++){
            if(ratings[i] > ratings[i-1]){
                candyNum[i] = candyNum[i-1] + 1;
            }
        }
        //从右到左遍历,保证反方向上等级越高的糖果数越多
        for(int i = len-2; i >= 0; i--){
            if(ratings[i] > ratings[i+1] && candyNum[i] <= candyNum[i+1]){
                candyNum[i] = candyNum[i+1] + 1;
            }
        }
        for(int i = 0; i < len; i++){
            sum += candyNum[i];
        }
        return sum;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38068229/article/details/87872025
今日推荐