Easy To Understand Java 4ms Solution With One Pass O(n)


  • 0
    G
    public class Solution {
        public int candy(int[] ratings) {
            int len = ratings.length;
            int res = len;
            int start = 0;
            int height = 0;
            for (int i = 0; i < len - 1; ) {
                while (i < len - 1 && ratings[i] == ratings[i + 1]) i++;
                start = i;
                while (i < len - 1 && ratings[i] < ratings[i + 1]) {
                    res += (i - start + 1);
                    i++;
                }
                height = i - start;
                start = i;
                while (i < len - 1 && ratings[i] > ratings[i + 1]) {
                    res += (i - start + 1);
                    i++;
                }
                height = Math.min(height, i - start);
                res -= height;
            }
            return res;
        }
    }

Log in to reply
 

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