Why is this O(n) showing tle for large test cases


#1

int Solution::maxcoin(vector &A) {
long long int i=0,j=A.size()-1,p=1,sum=0;
while(i<j)
{

    if(p==1)
    {if(A[i]-max(A[i+1],A[j])>A[j]-max(A[i],A[j-1]))
    {sum+=A[i];i++;}
    else
    {sum+=A[j];j--;}
    p=-1;
    }
    else
    {
        if(A[i]-max(A[i+1],A[j])>A[j]-max(A[i],A[j-1]))
        i++;
        else
        j--;
        p=1;
    }
}
return sum;

}