A nine-line solution in Java


  • -5
    J

    I know it requires O(n) space. But it is a good start before checking more sophisticated solutions.

    public int candy(int[] ratings) {
            int len = ratings.length;
            if (len < 2) return len;
            int[] candy = new int[len];
            for (int i = 1; i < len; i++) candy[i] = ratings[i] > ratings[i - 1]? candy[i - 1] + 1: 1;
            for (int i = len - 2 ; i >= 0; i--) 
                if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) candy[i] = candy[i + 1] + 1;
            int sum = 0;
            for (int i: candy) sum += i;
            return sum;
        }

  • 0
    J

    Seriously, I don't like the code style, it is hard to read...


  • 0
    Y

    Agreed, I just don't understand why people keeping doing this, actually you can put them into one line if you want, but what's the point?


Log in to reply
 

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