码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - candy

时间:2014-08-23 11:20:30      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   2014   log   amp   

被第二个条件给坑了

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.
条件二言下之意是如果两个相邻小孩的rating一样,那么它们的candy谁多谁少无所谓。

所以思路是从左遍历到右,再从右遍历到左,记录每个值左右方向的严格递增子序列的长度(如果没有形成严格递增序列,那么长度为0)。所以小孩i 应该得到糖果数量等于相应左(右)严格递增子序列的较大值+1。复杂度O(n)。


  有兴趣可以思考下如果再增加一个条件的其他解法,

   3: Children with the same rating should get the same candies with their neighbors.


class Solution {
public:
	int candy(vector<int> &ratings) {

		vector<int> l2rMax((int)ratings.size(), 0);
		vector<int> r2lMax((int)ratings.size(), 0);

		
		for (int i = 1; i < ratings.size(); i++)
		{
			if (ratings[i] > ratings[i - 1])
				l2rMax[i] = l2rMax[i - 1] + 1;
		}

		for (int i = ratings.size() - 2; i >= 0; i--)
		{
			if (ratings[i] > ratings[i + 1])
				r2lMax[i] = r2lMax[i + 1] + 1;
		}

		int sum = 0;
		for (int i = 0; i < ratings.size(); i++)
		{
			sum += 1;
			sum += (r2lMax[i] > l2rMax[i] ? r2lMax[i] : l2rMax[i]);
		}

		return sum;
	}
};


Leetcode - candy

标签:style   blog   color   io   for   ar   2014   log   amp   

原文地址:http://blog.csdn.net/tspatial_thunder/article/details/38776741

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