EASY solution check from left check from right and max of this is answer


#1

int Solution::candy(vector &A) {

//int ans1=0;
int n=A.size();
if(n==1 || n==0){
    return n;
}
int prev=0;
vector<int> v(n,1);
for(int i=0;i<n;i++){
    if(i==0 ){
        if(A[i]>A[i+1]){
            v[i] = v[i+1]+1;
        }
    }
    else if(i==n-1){
        if(A[i-1]<A[i]){
            v[i] =v[i-1]+1;
        }
    }
    else{int a ,b;
    a=b=1;
    if(A[i]>A[i-1]){
        b=v[i-1]+1;
    }
    if(A[i]>A[i+1]){
        a=v[i+1]+1;
    }
    v[i] =max(a,b);
    }
    
   // ans1 += v[i];
}

int ans=0;
vector<int> v1(n,1);
for(int i=n-1;i>=0;i--){
    if(i==0 ){
        if(A[i]>A[i+1]){
            v1[i] = v1[i+1]+1;
        }
    }
    else if(i==n-1){
        if(A[i-1]<A[i]){
            v1[i] =v1[i-1]+1;
        }
    }
    else{int a ,b;
    a=b=1;
    if(A[i]>A[i-1]){
        b=v1[i-1]+1;
    }
    if(A[i]>A[i+1]){
        a=v1[i+1]+1;
    }
    v1[i] =max(a,b);
    }
    
    //ans2 += v[i];
}
for(int i=0;i<n;i++){
    ans +=max(v1[i],v[i]);
}

return ans;

}