Took me a minute to realize a single pass doesn't cut it.
Use a two-pass greedy approach: first initialize each child with 1 candy, then scan left-to-right to ensure higher ratings get more candies than left neighbors, and finally scan right-to-left to handle right neighbors. Sum the candies for the minimum total. This runs in O(n) time and O(n) space.
Pro tip: Mention that this is a classic greedy problem where local optimal choices lead to a global optimum, and emphasize that the two passes are independent and necessary to satisfy both neighbor constraints. Also, note that the space can be optimized to O(1) if only the total is needed, but O(n) is acceptable for clarity.
Confirm understanding: each child gets at least one candy; if a child's rating is higher than an adjacent child, they must get more candies. The goal is to minimize the total candies.
Create an array of candies, all initialized to 1. Traverse from left to right: if current rating > previous rating, set candies[i] = candies[i-1] + 1.
Traverse from right to left: if current rating > next rating, set candies[i] = max(candies[i], candies[i+1] + 1) to satisfy the right neighbor constraint without breaking the left one.
Sum all values in the candies array and return the total. This is the minimum total candies required.
State time complexity O(n) and space O(n). Discuss edge cases: empty array, single child, strictly increasing/decreasing ratings, and equal ratings.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.