1. 程式人生 > >【LeetCode】#135分發糖果(Candy)

【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;
    }
}