40ms c++ solution


  • 1
    B
    class Solution {
    public:
        int candy(vector<int>& ratings) {
            int n = ratings.size();
            if (n < 1)
            {
                return 0;
            }
                   
            int buf[n];
            for (int i = 0; i < n; i++)
            {
                buf[i] = 1;
            }
                   
            for (int i = 1; i < n; i++)
            {
                if (ratings[i] > ratings[i-1])
                {
                    buf[i] = buf[i-1] + 1;
                }
            }
            for (int i = n-2; i >= 0; i--)
            {
                if (ratings[i] > ratings[i+1] && buf[i] <= buf[i+1])
                {
                    buf[i] =  buf[i+1] + 1;
                }
            }
               
            int result = 0;
            for (int i = 0; i < n; i++)
            {
                result += buf[i];
            }
                   
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.