Plz tell ,What is wrong with this solution?


#1
static bool compare(pair<int,int>& p1,pair<int,int>& p2)
{
    if(p1.first==p2.first)
       return p1.second> p2.second;
    return p1.first<p2.first;   
}
int Solution::candy(vector<int> &A) {
   vector<pair<int,int> > B;
    int n=A.size();
    if(n==0 || n==1)
      return n;
    for(int i=0;i<n;i++)
    {
       B.push_back({A[i],i});
    }
    sort(B.begin(),B.end(),compare);
    vector<int> candies(n,-1);
    for(auto itr : B)
    {
       // cout<<itr.first<<" "<<itr.second<<endl;
        int indi=itr.second;
        if(indi==0)
        {
            
            if(candies[1]==(-1))
               candies[0]=1;
            else
              {
                  candies[0]=candies[1];
                  if(A[0]>A[1])
                    candies[0]++;
                  
              }
        }
        else if(indi==n-1)
        {
             if(candies[n-2]==(-1))
               candies[n-1]=1;
            else
              candies[n-1]=candies[n-2]+1;
        }
        else
        {
            int val=max(candies[indi+1],candies[indi-1]);
            if(val==(-1))
              candies[indi]=1;
            else
              {
                  candies[indi]=val;
                  if(A[indi]!=A[indi+1] && A[indi]!=A[indi-1])
                    candies[indi]++;
              }
        }
    }
    int sum=0;
    for(auto num : candies)
      { sum+=num;}
    return sum;   
}