LeetCode135. Distributing candy (greedy algorithm)

Ideas:

Greedy: achieve global optimum through local optimum

This question: start from the left side first, if the child on the right has a higher ratings[i]>rating[i-1] than the child on the left , then give out one more candy tg[i]=tg[i-1]+1 ;

for(i=1;i<n;i++)

{

    if(ratings[i]>ratings[i-1])

    {

        tg[i]=tg[i-1]+1;

    }

    else{tg[i]=1;}

After left traversal:

ratings 3 5 8 5 3 1 2
tg 1 2 3 1 1 1 2

It can be seen from the figure that if the child's score decreases to the right, there will be a problem with the simple left traversal (I got stuck here at the beginning of this question), then we can try to traverse from right to left, If the child on the left has a higher score ratings[i-1]>rating[i] than the child on the right , and the child on the left does not have more candies than the child on the right tg[i-1]<=tg[i] , then send one more candy tg[ i-1]=tg[i]+1 ;

for(i=n-1;i>0;i--)

{

    if(ratings[i-1]>ratings[i]&&tg[i-1]<=tg[i])

        tg[i-1]=tg[i]+1;

}

ratings 3 5 8 5 3 1 2
tg 1 2 4 3 2 1 2

Finally, use a traversal to add all the children's candies together to get the minimum number of candies

for(i=0;i<n;i++)

    s+=tg[i];

AC code :

int candy(int* ratings, int ratingsSize){
int i,n=ratingsSize;
int tg[n];
tg[0]=1;
for(i=1;i<n;i++)
{
    if(ratings[i]>ratings[i-1])
    {
        tg[i]=tg[i-1]+1;
    }
    else{tg[i]=1;}
}
for(i=n-1;i>0;i--)
{
    if(ratings[i-1]>ratings[i]&&tg[i-1]<=tg[i])
    {
        tg[i-1]=tg[i]+1;
    }
}
int s=0;
for(i=0;i<n;i++)
{
    s+=tg[i];
}
return s;
}

Guess you like

Origin blog.csdn.net/GANTENJ/article/details/123082000