LeetCode-Candy

来源:互联网 发布:Linux解压并新建文件夹 编辑:程序博客网 时间:2024/06/07 12:40

1. Candy(Hard)

Description
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?

Analysis
分析题意,每个Children至少有一颗Candy,我们可以初始化每个Children的Candy的数量为1,然后比较每个Children的和他前后的Children的rating,如果他的rating高于前后的Children的,则他的Candy数量必须至少比其他两个Children的更大值大1。但是前后一起比较并不好实现,我们可以先正序遍历ratings,如果当前Children的rating大于前一个Children的rating,则他的Candy数比前一个大1。然后倒序遍历一个,做相同的操作,就可以满足题目要求。

代码:

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