leetcode, LC16: candy

1 题目描述

有N个小朋友站在一排,每个小朋友都有一个评分
你现在要按以下的规则给孩子们分糖果:

  • 每个小朋友至少要分得一颗糖果
  • 分数高的小朋友要他比旁边得分低的小朋友分得的糖果多

你最少要分发多少颗糖果?

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

输入

[1, 2, 2]

输出

4

2 解题思路

遍历每一个小朋友,如果ta比两边的小朋友分数高糖果却比两边的小朋友少,则继续给这个小朋友分糖果,一次遍历后判断当前情况是否满足题目条件,不满足则继续遍历。

3 代码实现

class Solution {
public:
    /**
     * 
     * @param ratings int整型vector 
     * @return int整型
     */
    int candy(vector<int>& ratings) {
        // write code here
        vector<int> vec(ratings.size(), 1);
        bool flag = true;
        while(flag){
            flag = false;
            for(int i = 0; i < vec.size(); i++){
                int left = (i-1<0?0:i-1);
                int right = (i+1>vec.size()-1?vec.size()-1:i+1);
                while(ratings[i] > ratings[left] && vec[i] <= vec[left])
                    vec[i]++;
                while(ratings[i] > ratings[right] && vec[i] <= vec[right])
                    vec[i]++;
            }
            for(int i = 0; i < vec.size(); i++){
                int left = (i-1<0?0:i-1);
                int right = (i+1>vec.size()-1?vec.size()-1:i+1);
                if((ratings[i] > ratings[left] && vec[i] <= vec[left])
                  || (ratings[i] > ratings[right] && vec[i] <= vec[right]))
                    flag = true;
            }
        }
        int sum = 0;
        for(int i = 0; i < vec.size(); i++)
            sum += vec[i];
        return sum;
    }
};

4 运行结果

运行时间:710ms
占用内存:1044k

你可能感兴趣的:(leetcode,leetcode,数据结构,算法)