135. Candy

Problem:
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.
Analysis:
Two pass, init every child with 1 candy.
1. Scan from left to right, if ratings[i] < ratings[i + 1], set candies[i + 1] to candies[i] + 1.
2. Scan from right to left, if ratings[i] > ratings[i+1], get the larger one of candies[i] and candies[i + 1] + 1. If we only get candies[i+1] + 1, this would break the first scan result. Make candies[i] too small.

Solution:

class Solution {
    public int candy(int[] ratings) {
        if (ratings == null || ratings.length == 0)
            return 0;
        int res = 0;
        int[] candies = new int[ratings.length];
        Arrays.fill(candies, 1);
        for (int i = 0; i < ratings.length - 1; i++) {
            if (ratings[i + 1] > ratings[i])
                candies[i + 1] = candies[i] + 1;
        }

        for (int  i = ratings.length - 1; i > 0; i--) {
            if (ratings[i - 1] > ratings[i]) {
                candies[i - 1] = candies[i] + 1;
            }
        }

        for (int n: candies) {
            res += n;
        }
        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List