虽然我知道最好不要写垃圾答案,但是这个真的戳笑点。第一次写出有时候可以ac有时候会runtime error的解法,真是在生死线上徘徊啊:
class Solution {
public:
int cand[1000] = {0};
int Most(int a, vector<int>& ratings){
if(cand[a] != 0){
return cand[a];
}
if(ratings[a] > ratings[a-1]) return Most(a-1, ratings) + 1;
else if(ratings[a] > ratings[a+1]) return Most(a+1, ratings) + 1;
else{
cand[a] = 1;
return 1;
}
}
int candy(vector<int>& ratings) {
ratings.insert(ratings.begin(), 10000000);
ratings.push_back(10000000);
int n = (int)ratings.size();
for(int i = 1; i<n-1; i++){
if(ratings[i] > ratings[i+1] && ratings[i] > ratings[i-1]){
cand[i] = max(Most(i-1,ratings), Most(i+1, ratings)) + 1;
}
else if(ratings[i] > ratings[i-1]){
cand[i] = Most(i-1, ratings) + 1;
}
else if(ratings[i] > ratings[i+1]){
cand[i] = Most(i+1,ratings) + 1;
}
else cand[i] = 1;
}
int ans = 0;
for(int i = 0; i<n; i++){
ans += cand[i];
}
return ans;
}
};
理解倒是很好理解,更简单的解法是,正向遍历一遍再逆向遍历一遍,要开学了很忧伤。
class Solution {
public:
int candy(vector<int>& ratings) {
int n=ratings.size();
int sum;
vector<int> nums(n,1);
for(int i=1;i<n;i++){
if(ratings[i]>ratings[i-1])
nums[i]=nums[i-1]+1;
}
sum=nums[n-1];
for(int i=n-2;i>=0;i--){
if(ratings[i]>ratings[i+1] && nums[i]<nums[i+1]+1)
nums[i]=nums[i+1]+1;
sum+=nums[i];
}
return sum;
}
};