首页 > 代码库 > [LeetCode]135 Candy

[LeetCode]135 Candy

https://oj.leetcode.com/problems/candy/

http://blog.csdn.net/linhuanmars/article/details/21424783

public class Solution {
    public int candy(int[] ratings) {
        
        // 从左边向右边 遍历
        // 如果 这个 比 前一个大, ++
        // 否则 持平
        // 这样保证左右 小孩 和他 右边的人比较 是合法的
        //
        // 同理 向 左边 遍历
        
        int len = ratings.length;
        
        int[] left = new int[len];
        left[0] = 1;
        for (int i = 1 ; i < len ; i ++)
        {
            left[i] = 1;
            if (ratings[i] > ratings[i - 1])
                left[i] = left[i - 1] + 1;
        }

        int[] right = new int[len];
        right[len - 1] = 1;
        for (int i = len - 2 ; i >= 0 ; i --)
        {
            right[i] = 1;
            if (ratings[i] > ratings[i + 1])
                right[i] = right[i + 1] + 1;
        }        
        
        int sum = 0;
        for (int i = 0 ; i < len ; i ++)
        {
            sum += Math.max(left[i], right[i]);
        }
        return sum;
    }
}


[LeetCode]135 Candy