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?

[分析] 开一个数组num[], num[i]表示位置i处的孩子分到的candy数。先从前往后扫描,确保ratings[i] > ratings[i - 1]时,num[i] > num[i - 1],然后从后往前扫描,确保ratings[i] > ratings[i + 1]时,num[i] > num[i + 1],两遍扫描后就能满足题意了,计算需要的candy总数。

public class Solution {
    public int candy(int[] ratings) {
        int N = ratings.length;
        int[] num = new int[N];
        for (int i = 1; i < N; i++) {
            if (ratings[i] > ratings[i - 1])
                num[i] = num[i - 1] + 1;
        }
        for (int i = N - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1] && (num[i] <= num[i + 1]))
                num[i] = num[i + 1] + 1;
        }
        int sum = N;
        for (int i = 0; i < N; i++) {
            sum += num[i];
        }
        return sum;
    }
}

你可能感兴趣的:(ca)