135. Candy

来源:互联网 发布:淘宝上买面膜可靠吗 编辑:程序博客网 时间:2024/04/29 04:11

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?

先将每一个人的初始糖果为0,从前往后遍历,当遇到当前的比值较上一个高的话,那么就让当前的糖果数需要比上一个的糖果数多,设为上一个的糖果数加一,然后从后往前遍历如果比后一个的比值高,那么就需要比较当前值与后一个值加一的值的大小选取最大的,然后就得到了满足要求的最少的解,最后求和返回就行了,总共的时间复杂度是O(n)


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

0 0
原创粉丝点击