LeetCode 135. Candy

来源:互联网 发布:淘宝中学生书包女韩版 编辑:程序博客网 时间:2024/05/21 22:27

题目要求:
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?

每个小朋友至少分到一块糖,且分数比周围小朋友高的小朋友分到的糖更多。求最少需要给多少块糖。
看到这道题我一开始的想法是将一个数组按递增递减划分:如[1 2 3 4 3 2 1],这个数组可分为两段:1~4上升,4~1下降。用cnt记录while循环中上升/下降个数,记录值自加且跳出while循环后cnt置1。后来运行的时候[1 2 4 4 3]没有通过。原因是这个想法只考虑了从左到右的顺序,而实际上a[3]的值是由a[4]确定的,所以需要遍历两次:从左到右一次,从右到左一次。用数组记录两次遍历中的值并取两次中的较大值。

C++代码如下:

class Solution {public:    int candy(vector<int>& ratings) {        int n = ratings.size();        vector<int> nums(n, 1);        for(int i=1; i<n; i++)        {            if(ratings[i-1]<ratings[i]) nums[i] = nums[i-1]+1;        }        for(int i=n-1; i>0; i--)        {            if(ratings[i-1]>ratings[i]) nums[i-1] = max(nums[i]+1, nums[i-1]);        }        int sum = 0;        for(int i=0; i<n; i++)            sum += nums[i];        return sum;    }};
原创粉丝点击