[LeetCode] Candy

来源:互联网 发布:高丝婴儿面膜知乎 编辑:程序博客网 时间:2024/05/16 16:01

问题:

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. 所有的小朋友都分配一个糖果;

1. 从左向右:这次遍历的目的是处理所有的ascending subsequences。对于i和i+1,如果rating[i] < rating[i+1],那么后面的那一个的糖果一定要比前面的那个人多一个;

2. 从右向左:这次便利的目的是处理所有的descending subsequences。对于i和i - 1,如果input[i-1] > input[i]并且i-1的糖果还不比i的糖果多的话,那么首先他们的糖果一定一样多,所以也只要把i-1的糖果加1即可。


代码:(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+1])candy[i] = candy[i + 1] + 1;}int result = 0;for (int i = 0; i < candy.size(); i ++)result += candy[i];return result;}};


0 0