Candy--LeetCode 傷城~ 2022-08-07 13:50 138阅读 0赞 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? 这道题用到的思路和Trapping Rain Water是一样的,用动态规划。基本思路就是进行两次扫描,一次从左往右,一次从右往左。第一次扫描的时候维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中,第二次扫描的时候维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中。这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。方法只需要两次扫描,所以时间复杂度是O(2\*n)=O(n)。空间上需要一个长度为n的数组,复杂度是O(n)。代码如下: int candy(vector<int> &ratings) { vector<int> candy(ratings.size(),1); int sum,i; for(i=1;i<ratings.size();i++) { if(ratings[i] > ratings[i-1]) candy[i] = candy[i-1]+1; } sum = candy[ratings.size()-1]; for(i=ratings.size()-2;i>=0;i--) { int cur =1; if(ratings[i] > ratings[i+1]) cur = candy[i+1]+1; sum += max(cur,candy[i]); candy[i] = cur; } } 如果上面的那个不好理解,看下面的代码 int candy(vector<int> &ratings) { vector<int> candy(ratings.size(),1); int sum,i; for(i=1;i<ratings.size();i++) { if(ratings[i] > ratings[i-1]) candy[i] = candy[i-1]+1; } sum = candy[ratings.size()-1]; for(i=ratings.size()-2;i>=0;i--) { int cur =1; if(ratings[i] > ratings[i+1] && candy[i] < candy[i+1]) candy[i] = candy[i+1]+1; sum += candy[i]; } return sum; } 相当于左右开弓,分别计算最小值,然后就可以了,但是需要注意的是 if(ratings[i] > ratings[i+1] && candy[i] < candy[i+1]) //后半部分的判断尤其重要
还没有评论,来说两句吧...