> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/135.-candy.md).

# 135. Candy

![](/files/-MhvLaPA5chMvZTyoAHB)

![](/files/-MhvLf2MJKzFGsM3xblt)

time: O(n)

space: O(n)

```java
class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int candy[] = new int[n];
        Arrays.fill(candy, 1);
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i-1]) {
                candy[i] = Math.max(1, candy[i-1]+1);
            }
        }
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i+1]) {
                candy[i] = Math.max(candy[i], candy[i+1]+1);
            }
        }
        int sum = 0;
        for (int c : candy) {
            sum += c;
        }
        return sum;
        // return Arrays.stream(candy).sum();
    }
}

/*
Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, 
second and third child with 2, 1, 2 candies respectively.

look from left first 
1,   0,  2  [ratings]

1,   1,  1  [candy]
---------------------
1,   1,  1  [candy] 
i-1  i

1,   1,  1to2
    i-1  i 
----------------------

look from right
1,      1,  2  [candy]
        i   i+1

1to2,   1,  2 
       i+1
i
 
*/
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/135.-candy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
