zoukankan      html  css  js  c++  java
  • 【LeetCode】135. Candy

    Candy

    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?

    左右各遍历一次,依据前一个位置的candy数计算当前位置需要的最小candy数(最少为1)

    由于两次遍历的结果都要满足,因此对同一位置取max即可。

    class Solution {
    public:
        int candy(vector<int>& ratings) {
            if(ratings.empty())
                return 0;
            int n = ratings.size();
            vector<int> left(n, 1);
            for(int i = 1; i < n; i ++)
            {
                if(ratings[i] > ratings[i-1])
                    left[i] = left[i-1] + 1;
            }
            vector<int> right(n, 1);
            int sum = max(left[n-1], right[n-1]);
            for(int i = n-2; i >= 0; i --)
            {
                if(ratings[i] > ratings[i+1])
                    right[i] = right[i+1] + 1;
                sum += max(left[i], right[i]);
            }
            return sum;
        }
    };

  • 相关阅读:
    复习一些奇怪的题目
    NOIP 考前 KMP练习
    NOIP 考前 并查集复习
    NOIP 考前 Tarjan复习
    NOIP 考前 图论练习
    BZOJ 1468 树分治
    Codeforces Round #376 (Div. 2)
    CodeVS 线段覆盖1~5
    Luogu 3396 权值分块
    BZOJ 2743 树状数组
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4115571.html
Copyright © 2011-2022 走看看