solution.cpp 572 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class Solution
{
public:
    int candy(vector<int> &ratings)
    {
        int n = ratings.size();
        int ans = 0;
        vector<int> sum(n, 1);
        if (n < 2)
            return n;
        for (int i = 0; i < n; ++i)
        {
            if (i > 0 && ratings[i] > ratings[i - 1])
                sum[i] = sum[i - 1] + 1;
        }
        for (int i = n - 1; i >= 0; --i)
        {
            if (i < n - 1 && ratings[i] > ratings[i + 1])
                sum[i] = max(sum[i + 1] + 1, sum[i]);
            ans += sum[i];
        }
        return ans;
    }
};