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**/);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • There are N children standing in a line. Each child is as...
    ShutLove阅读 2,939评论 0 0
  • There are N children standing in a line. Each child is as...
    juexin阅读 1,644评论 0 0
  • 问题分析 There are N children standing in a line. Each child ...
    codingXue阅读 1,007评论 0 0
  • There are N children standing in a line. Each child is as...
    Jeanz阅读 988评论 0 0