LEETCODE: Candy
2015-01-06 22:33
381 查看
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.从左往右扫描,如果右边比左边大,那么右边的是左边的 + 1。
2.从右往左扫描,如果左边比右边大,那么左边的是右边的 + 1 和自己原有的值中那个比较大的数。
3.把1,2扫描所得的结果相加,记住每个孩子都要给糖果,所以各个数还要+ 1。
class Solution {
public:
int candy(vector<int> &ratings) {
if(ratings.size() == 0) return 0;
vector<int> candies(ratings.size());
for(int ii = 1; ii < ratings.size(); ii ++) {
if(ratings[ii] > ratings[ii - 1]) {
candies[ii] = candies[ii - 1] + 1;
}
}
for(int ii = ratings.size() - 1; ii >= 0; ii --) {
if(ratings[ii] < ratings[ii - 1]) {
candies[ii - 1] = max(candies[ii] + 1, candies[ii - 1]);
}
}
int total = 0;
for(int ii = 0; ii < candies.size(); ii ++) {
total += candies[ii] + 1;
}
return total;
}
};
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.从左往右扫描,如果右边比左边大,那么右边的是左边的 + 1。
2.从右往左扫描,如果左边比右边大,那么左边的是右边的 + 1 和自己原有的值中那个比较大的数。
3.把1,2扫描所得的结果相加,记住每个孩子都要给糖果,所以各个数还要+ 1。
class Solution {
public:
int candy(vector<int> &ratings) {
if(ratings.size() == 0) return 0;
vector<int> candies(ratings.size());
for(int ii = 1; ii < ratings.size(); ii ++) {
if(ratings[ii] > ratings[ii - 1]) {
candies[ii] = candies[ii - 1] + 1;
}
}
for(int ii = ratings.size() - 1; ii >= 0; ii --) {
if(ratings[ii] < ratings[ii - 1]) {
candies[ii - 1] = max(candies[ii] + 1, candies[ii - 1]);
}
}
int total = 0;
for(int ii = 0; ii < candies.size(); ii ++) {
total += candies[ii] + 1;
}
return total;
}
};
相关文章推荐
- leetcode_Candy
- LeetCode:Candy
- 4.19 leetcode -19 candy
- LeetCode 135:candy 题解 Python
- leetcode:Candy
- 117_leetcode_Candy
- [LeetCode] Candy
- leetcode :Candy
- [LeetCode]Candy
- https://leetcode.com/problems/candy/
- Candy -- leetcode
- LeetCode:Candy
- LeetCode_Candy
- leetcode candy
- LeetCode139: Candy
- 【leetcode】Candy
- LeetCode-Candy-分糖果-逻辑关系
- Leetcode 135 Candy
- LeetCode || Candy
- [leetcode]Candy @ Python