Candy_Week7
题目说明:
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?
难度: Hard
解题思路:
题目意为,若干个孩子站成一排,每个孩子都有rating,比较相邻的孩子,rating高的要比rating低的(相邻的)孩子糖果多。
且每个孩子至少有一颗糖,问最少共需要多少颗糖
思路为:
建立candy数组,里面存放每个孩子的糖果数量
顺序遍历rating数组,当右边的孩子rating高的时候,确保他比左边孩子多一个糖,不然(小于或等于)则设置糖果数为1
逆序遍历rating数组,确认是否存在左边孩子rating比右边孩子高的情况,若存在且糖果数确实少,则为其增加糖果,直到比右边孩子高
两次遍历数组即可得出结果
用了O(n)的时间和O(n)的空间
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
int total = 0;
int length = ratings.size();
//标记每个孩子手中的糖果数量
vector<int> candy(length);
candy[0] = 1;
//顺序遍历数组,确保当左边孩子比右边孩子rating高时,糖果多1
for (int i = 1;i < length; i++) {
if (ratings[i] > ratings[i-1]) {
candy[i] = candy[i-1] + 1;
} else {
candy[i] = 1;
}
}
//逆序遍历数组,确认是否存在右边孩子比左边孩子rating高情况,若存在,则确保其糖果比左边孩子多1
for (int i = length-2; i >= 0; i--) {
if (ratings[i] > ratings[i+1] && candy[i] < (candy[i+1]+1)) {
candy[i] = candy[i+1] + 1;
}
total += candy[i];
}
total += candy[length-1];
return total;
}
};