首页 > 代码库 > Candy
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?
思路:分糖果问题,用贪心算法。我们用num[i]表示第i个孩子的糖果数目,如果i+1孩子比i孩子的ratings大,则i+1的孩子糖果数目为i孩子糖果数目+1.如果i孩子比i+1孩子ratings大,怎么办,等从左往右开始遍历结束,我们从右往左开始,把之前忽略的情况给补上,就可以了。时间复杂度为O(n),空间复杂度为O(n)。
class Solution {public: int candy(vector<int> &ratings) { int n=ratings.size(); if(n<=0) return 0; vector<int> num(n,1); for(int i=1;i<n;i++) { if(ratings[i-1]<ratings[i]) { num[i]=num[i-1]+1; } } for(int i=n-2;i>=0;i--) { if(ratings[i]>ratings[i+1] && num[i]<=num[i+1]) { num[i]=num[i+1]+1; } } int sum=0; for(int i=0;i<n;i++) { sum+=num[i]; } return sum; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。