135. Candy

weixin_34342992發表於2018-04-07

題目分析

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?

可以用貪心演算法來解出這道題目。

程式碼

public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0) {
            return 0;
        } 
        if(ratings.length == 1) {
            return 1;
        }
        int sum = 0;
        int[] candys = new int[ratings.length];
        // 第一個孩子先只分一塊糖
        candys[0] = 1;
        for(int i = 1; i < ratings.length; i++) {
            // 如果當前的孩子的等級的比左邊的高
            if(ratings[i] > ratings[i - 1]) {
                // 右邊的孩子的糖果數比左邊的多一
                candys[i] = candys[i - 1] + 1;
            } else {
                candys[i] = 1;
            }
        }
        sum += candys[candys.length - 1];
        for(int i = ratings.length - 2; i >= 0; i--) {
            // 如果當前孩子的等級比右邊的孩子高
            if(ratings[i] > ratings[i + 1]) {
                candys[i] = Math.max(candys[i], candys[i + 1] + 1);
            }
            sum += candys[i];
        }
        return sum;
    }
}

相關文章