Time complexity O(n) and constant space O(1 ) Java Solution


  • -1
    M
    public int candy(int[] ratings) {
        if(ratings.length == 1) return 1;
        int result = 1;
        int max = 1;
        int max_index = 0;
        int previous = 1;
        for(int i = 1; i < ratings.length; i++)
        {
            if(ratings[i] > ratings[i-1])
            {
                max_index = i;
                previous++;
                max = previous;
                result += previous;
            }
            else if(ratings[i] == ratings[i-1])
            {
                max = 1;
                max_index = i;
                previous = 1;
                result++;
            }
            else
            {
                previous = 1;
                if(i < max_index + max)
                    result += (i-max_index);
                else
                    result += (i-max_index+1);
            }
        }
        return result;
    }

Log in to reply
 

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