# Getting wrong answer on leetcode but correct on ideone for same input

• ``````class Solution {
public:
int candy(vector<int>& ratings) {
if(ratings.size()<=1)
return ratings.size();

vector<int> candies;
for(int i=0;i<ratings.size();i++)
candies.push_back(0);
for(int i=1;i<ratings.size()-1;i++)
if(ratings[i]<=ratings[i-1] && ratings[i]<=ratings[i+1])
candies[i]=1;
if(ratings[0]<=ratings[1])
candies[0]=1;
if(ratings[ratings.size()-1]<=ratings[ratings.size()-2])
candies[ratings.size()-1]=1;
for(int i=1;i<ratings.size()-1;i++)
if(ratings[i]>ratings[i-1] && ratings[i]<=ratings[i+1])
candies[i]=candies[i-1]+1;
for(int i=ratings.size()-1;i>0;i--)
if(ratings[i]<=ratings[i-1] && ratings[i]>ratings[i+1])
candies[i]=candies[i+1]+1;
if(ratings[0]>ratings[1])
candies[0]=candies[1]+1;
if(ratings[ratings.size()-1]>ratings[ratings.size()-2])
candies[ratings.size()-1]=candies[ratings.size()-2]+1;
for(int i=1;i<ratings.size()-1;i++)
if(ratings[i]>ratings[i-1] && ratings[i]>ratings[i+1])
candies[i]=max(candies[i-1],candies[i+1])+1;
int sum=0;
for(int i=0;i<candies.size();i++)
sum+=candies[i];
return sum;
}
};
``````

Input for wrong answer : [1,2,2]

Correct Output : 4

Getting on Leetcode : 32548

If I run it manually on Leetcode as custom input, I get answer 4.

• Due to

``````    for(int i=ratings.size()-1;i>0;i--)
``````

you're accessing an invalid index when you do `ratings[i+1]` the first time.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.