码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] Candy

时间:2015-08-01 23:40:01      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   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?

题意:

N个小孩站成一列.每个小孩都有一个分数.

你按照以下的规则,把这些糖果分给这些小孩:

    1. 每个小孩至少有一个糖.

    2.得分高的小孩比他的邻居小孩有更多的糖果.

你能分出的最少的糖果的数目是多少.


算法分析:

 *  根据题意,思路可以如下:

 *  初始化数组dp,数组成员均为1,每个孩子先分配一个糖果

 *  从左向右遍历,如果第i个孩子比第i - 1孩子等级高,则dp[i] = dp[i - 1] + 1

 *  从右向左遍历,如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少,则dp[i] = dp[i + 1] + 1

 *  这种思路实现的算法复杂度为O(n)

   整体思路图如下参考博客http://blog.csdn.net/lanxu_yy/article/details/17752273

  技术分享


AC代码:

<span style="font-family:Microsoft YaHei;font-size:10px;">public class Solution
{
    public int candy(int[] ratings) 
    {
        if (ratings == null || ratings.length == 0)
            return 0;
            
        ArrayList<Integer> dp = new ArrayList<Integer>();
        
        for (int i = 0; i < ratings.length; i++) 
            dp.add(i, 1);

        for (int i = 1; i < ratings.length; i++) 
            if (ratings[i] > ratings[i - 1])
                dp.set(i, dp.get(i - 1) + 1);

        for (int i = ratings.length - 2; i >= 0; i--) 
            if (ratings[i] > ratings[i + 1] && dp.get(i) <= dp.get(i + 1)) 
                dp.set(i, dp.get(i + 1) + 1);

        int res = 0;

        for (int i = 0; i < dp.size(); i++)
            res += dp.get(i);

        return res;
    }
}</span>

版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Candy

标签:leetcode   java   candy   

原文地址:http://blog.csdn.net/evan123mg/article/details/47190879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!