LeetCode – Candy (Java)

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:

1. Each child must have at least one candy.
2. Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Analysis

This problem can be solved in O(n) time.

We can always assign a neighbor with 1 more if the neighbor has higher a rating value. However, to get the minimum total number, we should always start adding 1s in the ascending order. We can solve this problem by scanning the array from both sides. First, scan the array from left to right, and assign values for all the ascending pairs. Then scan from right to left and assign values to descending pairs.

This problem is similar to Trapping Rain Water.

Java Solution

public int candy(int[] ratings) {
	if (ratings == null || ratings.length == 0) {
		return 0;
	}
 
	int[] candies = new int[ratings.length];
	candies[0] = 1;
 
	//from let to right
	for (int i = 1; i < ratings.length; i++) {
		if (ratings[i] > ratings[i - 1]) {
			candies[i] = candies[i - 1] + 1;
		} else { 
			// if not ascending, assign 1
			candies[i] = 1;
		}
	}
 
	int result = candies[ratings.length - 1];
 
	//from right to left
	for (int i = ratings.length - 2; i >= 0; i--) {
		int cur = 1;
		if (ratings[i] > ratings[i + 1]) {
			cur = candies[i + 1] + 1;
		}
 
		result += Math.max(cur, candies[i]);
		candies[i] = cur;
	}
 
	return result;
}

21 thoughts on “LeetCode – Candy (Java)”

  1. ARE U RETARTED GET A JOB NIGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA


  2. class Solution {
    public:
    int candy(vector& ratings) {
    if(ratings.size() == 0) return 0;
    vector minNeededFromLeftSide(ratings.size()), minNeededFromRightSide(ratings.size());
    minNeededFromLeftSide[0] = 1;
    minNeededFromRightSide[ratings.size() - 1] = 1;
    for(int i = 1, j = ratings.size() - 2; i = 0; i++, j--) {
    minNeededFromLeftSide[i] = (ratings[i] > ratings[i - 1]) * minNeededFromLeftSide[i - 1] + 1;
    minNeededFromRightSide[j] = (ratings[j] > ratings[j + 1]) * minNeededFromRightSide[j + 1] + 1;
    }
    int ans = 0;
    for(int i = 0; i < ratings.size(); i++) {
    ans += max(minNeededFromLeftSide[i], minNeededFromRightSide[i]);
    }
    return ans;
    }
    };

  3. 1, 2, 1, 1, 1, 1 is wrong because 2 last element couldn’t have same amount of candies they have different priority.

  4. Solution in Python:

    ratings = [1, 4, 3, 3, 3, 1]
    ratings2 = []
    ratings3 = [0]
    ratings4 = [10]

    def candy(ratings):
    print(ratings)
    size = len(ratings)
    if size == 0:
    return 0
    if size == 1:
    return 1

    candies = [1 for i in range(size)]
    for i in range(size – 1):
    if ratings[i] > ratings[i+1] and candies[i] ratings[j – 1] and candies[j] <= candies[j – 1]:
    candies[j] += 1
    return candies

    # —–
    if __name__=="__main__":
    print(candy(ratings))
    print(candy(ratings2))
    print(candy(ratings3))
    print(candy(ratings4))

  5. It is required, else you may reduce the value of candies[i]
    For eg priority = [2,3,4,5,6,1] if after left run you have [1,2,3,4,5,1]
    when you do the right run it will see priority[4]>priority[5] so it will put candies[4] = candies[4]+1, which is 2.
    so after right run candies = [2,3,4,5,2,1] which is wrong.

  6. Still this case that wouldn’t work : ratings [1,2,3,3,3,3]

    Then we should test the same ratings values for differents candies from left to right as well

  7. For the second for loop going from right to left, no need for current pointers or any other Math.max routine.
    The following would work too:

    // from right to left
    for (int i = ratings.length - 2; i >= 0; i--) {
    if (ratings[i] > ratings[i + 1]) {
    candies[i] = candies[i + 1] + 1;
    }

    result = result + candies[i];
    }

  8. static int getMinCandies(int[] ratings){
    int candies[]=new int[ratings.length];
    Arrays.fill(candies, 1);
    for(int i=0 ; i =0 && i+1 ratings[i-1] ) {
    candies[i] = candies[i-1]+1;
    }

    if(ratings[i] =0 ; i--) {
    if(i-1> = 0 && i+1 ratings[i+1]) {
    candies[i] = candies[i+1]+1;
    }

    }
    result+=candies[i];

    }
    return result;
    }

  9. Simple solution, O(n) time and O(1) space:

    public int candy(int [] ratings) {
    if (ratings == null) {
    return 0;
    }

    int extras = 0;

    for (int i=0; i 0 && ratings[i] > ratings[i-1]) {
    extras++;
    } else if (i+1 ratings[i+1]) {
    extras++;
    }
    }

    return extras + ratings.length;
    }

  10. Not sure why the result of {1, 4, 3, 3, 3, 1} is expected to be {1, 2, 1, 1, 2, 1} since the item at position 4 (3) is not greater than it’s neighbors (3 and 1) like the requirements ask for (3 is not greater than 3).
    I think the correct result should be {1, 2, 1, 1, 1, 1}

    And according to that i did this code:

    public static int[] candy(int[] ratings) {
    int[] newCandies = new int[ratings.length];
    for (int i = 1; i 0 ? 1 : 0;
    if (newCandies[i - 1] < tmp) {
    newCandies[i - 1] = tmp;
    }
    tmp = prev < curr && next < curr ? 2 : 1;
    if (newCandies[i] 0 ? 1 : 0;
    if (newCandies[i + 1] < tmp) {
    newCandies[i + 1] = tmp;
    }
    }
    return newCandies;
    }

    @Test
    public void testGetCandies() {
    assertEquals(Arrays.toString(new int[]{1, 2, 1, 1, 1, 1}), Arrays.toString(ChildCandies.candy(new int[]{1, 4, 3, 3, 3, 1})));
    assertEquals(Arrays.toString(new int[]{1, 1, 2, 1, 1, 1}), Arrays.toString(ChildCandies.candy(new int[]{1, 1, 4, 3, 2, 2})));
    assertEquals(Arrays.toString(new int[]{1, 2, 1, 2, 1, 1}), Arrays.toString(ChildCandies.candy(new int[]{2, 3, 1, 3, 1, 1})));
    }

  11. The problem does not require to consider the same rating situation.
    If the ratings is [1, 4, 3, 3, 3, 1], then the candy counts would be [1, 2, 1, 1, 2, 1].

  12. This solution wouldn’t work if you have the same ratings for consecutive neighbors. e.g :

    int[] ratings = new int[]{1 ,4, 3,3,3, 1};

    We have to check if the neighbors have the same rating but different candies when going from right to left. Here is a working solution :

    public int getcandy(int[] ratings) {

    int[] candies = new int[ratings.length];

    candies[0] = 1;

    //from left to right

    for (int i = 1; i ratings[i – 1])

    candies[i] = candies[i – 1] + 1;

    else

    candies[i] = 1;

    }

    int result = candies[ratings.length – 1];

    //from right to left

    for (int i = ratings.length – 2; i >= 0; i–) {

    int curr = 1;

    if (ratings[i] > ratings[i + 1])

    curr = candies[i + 1] + 1;

    // consider same rating neighbors with different candies

    else if (ratings[i] == ratings[i + 1] && candies[i] < candies[i + 1])

    curr = candies[i + 1];

    candies[i] = Math.max(curr, candies[i]);

    result += candies[i];

    }

    return result;

    }

  13. This solution wouldn’t work if you have the same ratings for consecutive neighbors. e.g :

    int[] ratings = new int[]{1 ,4, 3,3,3, 1};

    We have to check if the neighbors have the same rating but different candies when going from right to left. Here is a working solution :

    public int getcandy(int[] ratings) {

    int[] candies = new int[ratings.length];

    candies[0] = 1;

    //from left to right

    for (int i = 1; i ratings[i – 1])

    candies[i] = candies[i – 1] + 1;

    else

    candies[i] = 1;

    }

    int result = candies[ratings.length – 1];

    //from right to left

    for (int i = ratings.length – 2; i >= 0; i–) {

    int curr = 1;

    if (ratings[i] > ratings[i + 1])

    curr = candies[i + 1] + 1;

    // consider same rating neighbors with different candies

    else if (ratings[i] == ratings[i + 1]

    && candies[i] < candies[i + 1])

    curr = candies[i + 1];

    candies[i] = Math.max(curr, candies[i]);

    result += candies[i];

    }

    return result;

    }

Leave a Comment