O(n) time O(n) space C++


#1

#include
int Solution::candy(vector &A) {
int n=A.size();
if(n==0){
return n;
}
vectorcandy(n,1);//array with one candy to each child.
for(int i=1;i<n;i++)//forward loop
{
if(A[i]>A[i-1]&&candy[i]<=candy[i-1])//if current rating is higher than previous rating
{
candy[i]=1+candy[i-1];
}
}
for(int i=n-2;i>=0;i–)//backward loop
{
if(A[i]>A[i+1]&&candy[i]<=candy[i+1])//if currernt rating is lower than the rating of the child after
{
candy[i]=1+candy[i+1];
}
}
// for(int i=0;i<n;i++){
// cout<<A[i]<<" “;
// }
// cout<<endl;
// for(int i=0;i<n;i++){
// cout<<choco[i]<<” ";
// }
return accumulate(candy.begin(),candy.end(),0);//return sum
}


#2

//if currernt rating is lower than the rating of the child after
is vale comment ka kya mtlb h ji??