135. 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?

Solution

var candy = function(ratings) {
    var result = 0;
    var candy = new Array();
    for(var i = 0; i < ratings.length; i++) {
        if(i - 1 < 0 || ratings[i - 1] >= ratings[i]) 
            candy[i] = 1;
        else candy[i] = candy[i - 1] + 1;
    }
    for(var j = ratings.length - 1; j >= 0; j--) {
        if(j + 1 < ratings.length && ratings[j + 1] < ratings[j]) 
            candy[j] = Math.max(candy[j + 1] + 1, candy[j]);
    }
    for(var k = 0; k < ratings.length; k++) {
        result += candy[k];
    }
    return result;
};

JavaScript min & max 函数:
Math.min(a, b);
Math.max(a, b);

JavaScript 输出
Console.log(/**whatYouWantToOutput**/);

你可能感兴趣的:(135. Candy)