Someone tell me whats wrong


#1

can some one tell me whats wrong with my code

int Solution::candy(vector &A) {
int n=A.size();
int dp[n];
int flag=1;
int sum=0;
for(int i=0;i<n;i++){
dp[i]=1;
}
for(int i=1;i<A.size();i++){
if(A[i]==A[i-1])
continue;

   else if(A[i]>A[i-1] && dp[i]<=dp[i-1] )
    dp[i]=dp[i]+1;
    
    else if(A[i-1]>A[i] && dp[i-1]<=dp[i] ){
        dp[i-1]=dp[i]+1;
        if(i-1!=0)
         i=i-2;
    }
}

int ag=0;
for(int i=0;i<n;i++)
ag+=dp[i];

return ag;

}


#2

The problem is you can’t do it in 1 pass. because for prev number you can check if current rating is more then prev then you max(cur, prev+1).

But how do you find next one. since at starting all are ones then you can’t just check next value in one traversal because best answer of i+1 is still not calculated and i is depend on i+1.

so make 2 traversal with same logic

  • first is for i=1 to n
  • second is for i=n-2 to 0