This page explains Java solution to problem `Candy`

using `Array`

data structure.

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?

Input: [1,0,2]Output: 5Explanation:

You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Input: A = [1,2,2]Output: 4Explanation:

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.

```
package com.vc.hard;
import java.util.*;
class Candy {
public int candy(int[] ratings) {
if(ratings == null) return 0;
int n = ratings.length;
int[] left = new int[n];
Arrays.fill(left, 1);
for(int i = 1; i < n; i++) {
int leftElement = ratings[i - 1];
int currentElement = ratings[i];
if(leftElement < currentElement) left[i] = left[i - 1] + 1;
}
int[] right = new int[n];
Arrays.fill(right, 1);
for(int i = n - 2; i >= 0; i--) {
int rightElement = ratings[i + 1];
int currentElement = ratings[i];
if(rightElement < currentElement) right[i] = right[i + 1] + 1;
}
int res = 0;
for(int i = 0; i < n; i++) res += Math.max(left[i], right[i]);
return res;
}
}
```

O(N) Where

N is total number of children standing in a line

O(N) Where

N is total number of children standing in a line