[leetcode] 【数组】 135. Candy
2016-05-29 23:23
477 查看
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?
你要给小孩按下面规则发糖:
每个小孩至少发一个
较高评估值的小孩得到的糖要比旁边的小孩多
问最少需要发多少糖?
然后从右往左遍历,同样,如果左边的估值大,则左边的数要比右边的数大或者为右边的数+1.
这样得到的结果就是每个小孩得到的糖数。
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.然后从右往左遍历,同样,如果左边的估值大,则左边的数要比右边的数大或者为右边的数+1.
这样得到的结果就是每个小孩得到的糖数。
accumulate(&candynum[0],&candynum[0]+len,len)这个函数把所有小孩得到的糖相加,初始值为小孩数量。
class Solution { public: int candy(vector<int>& ratings) { const int len=ratings.size(); vector<int> candynum(len); for(int i=1;i<len;i++) { if(ratings[i]>ratings[i-1]) candynum[i]=max(candynum[i],candynum[i-1]+1); } for(int i=len-2;i>=0;i--) { if(ratings[i]>ratings[i+1]) candynum[i]=max(candynum[i],candynum[i+1]+1); } return accumulate(&candynum[0],&candynum[0]+len,len); } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解