# 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 = 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; }```
Category >> Algorithms >> Interview >> Java
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• West

here should be mention that same priority kids can have different amount of candy

• West

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

Solution in Python:

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

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))

• Zaid Haq

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>priority so it will put candies = candies+1, which is 2.
so after right run candies = [2,3,4,5,2,1] which is wrong.

• Toufik-Yassine L

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

• Ankit Shah

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]; } ```

• Mel

``` 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; } ```

• Harsh

Ignore that, I did not understand the question correctly.

• Harsh

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; } ```

• Juan Melo

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}))); } ```

• I think in your second loop, last two lines should be replaced by following 3 lines.
cur = Math.max(cur, candies[i]);
result += cur;
candies[i] = cur;

• guest

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].

• Taoufik Bdiri

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 = 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;

}

• 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 = 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;

}