【LeetCode】#135分发糖果(Candy)

【LeetCode】#135分发糖果(Candy)

题目描述

老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
你需要按照以下要求,帮助老师给这些孩子分发糖果:
1.每个孩子至少分配到 1 个糖果。
2.相邻的孩子中,评分高的孩子必须获得更多的糖果。
那么这样下来,老师至少需要准备多少颗糖果呢?

示例

示例 1:

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

示例 2:

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

Description

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:
1.Each child must have at least one candy.
2.Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?

Example

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.

解法

class Solution {
    public int candy(int[] ratings) {
        if(ratings==null || ratings.length==0)
            return 0;
        int[] nums = new int[ratings.length];
        for(int i=0; i<ratings.length; i++){
            nums[i] = 1;
        }
        for(int i=1; i<ratings.length; i++){
            if(ratings[i]>ratings[i-1] && nums[i]<=nums[i-1]){
                nums[i] = nums[i-1]+1;
            }
        }
        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 sum = 0;
        for(int i : nums){
            sum += i;
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/85099888
今日推荐