Leetcode Candy

来源:互联网 发布:环刀法压实度软件 编辑:程序博客网 时间:2024/06/14 01:29

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?


因为至少有一个糖果,初始时将candy数组赋值为1.因为高rating的children要比neighbors获得更多的糖果。所以先进行一次遍历,高rating的children的糖果数比前一个children 多1.但这样处理完,还存在一种不符合情况的没有处理。前一个children的糖果数为1,而后一个rating更低的children糖果数也为1,这样是不符合题目要求的。因此从尾到头开始遍历,如果前一个children的rating大于后一个children,则设置其糖果数为max(candy[i],candy[i+1]) ,这样就修正了该情况,同时也会因为该修改而修改其他children的糖果数,从而符合题目要求。

代码如下:

class Solution {public:    int candy(vector<int>& ratings) {        int num = ratings.size();        int candy[num],total=0;;        for(int i=0;i<num;i++)            candy[i] = 1;                for(int i=1;i<num;i++)        {            if(ratings[i] > ratings[i-1])                candy[i] = candy[i-1]+1;        }                total = candy[num-1];        for(int i=num-2;i>=0;i--)        {            if(ratings[i] > ratings[i+1])            {                candy[i] = max(candy[i],candy[i+1]+1);            }            total += candy[i];        }                return total;    }};