135. Candy
Asked at 17Bloomberg55Amazon53Google47Microsoft46Meta34Infosys50Dropbox68SAP62Morgan Stanley54Walmart Labs53Uber44Accenture44Intuit43Visa39Goldman Sachs36TikTok35Oracle27
Problem
Children stand in a line with ratings. Give each child at least one candy, and a child with a higher rating than a neighbour must get more candies than that neighbour. Return the minimum total candies.
Example: [1,0,2] → 5 (2, 1, 2); [1,2,2] → 4 (1, 2, 1)
Constraints: n ≤ 2·10⁴.
Left→right pass satisfies "higher than left neighbour"; right→left pass satisfies "higher than right neighbour" while keeping the max.
ratings 1 0 2
L->R 1 1 2
R->L 2 1 2 total 5
Complexity: O(n).
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
c = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
c[i] = c[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
c[i] = max(c[i], c[i + 1] + 1)
return sum(c)
assert Solution().candy([1, 0, 2]) == 5
assert Solution().candy([1, 2, 2]) == 4
class Solution {
public int candy(int[] ratings) {
int n = ratings.length, total = 0;
int[] c = new int[n];
Arrays.fill(c, 1);
for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) c[i] = c[i - 1] + 1;
for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) c[i] = Math.max(c[i], c[i + 1] + 1);
for (int x : c) total += x;
return total;
}
}
func candy(ratings []int) int {
n := len(ratings)
c := make([]int, n)
for i := range c {
c[i] = 1
}
for i := 1; i < n; i++ { // left neighbour rule
if ratings[i] > ratings[i-1] {
c[i] = c[i-1] + 1
}
}
total := c[n-1]
for i := n - 2; i >= 0; i-- { // right neighbour rule
if ratings[i] > ratings[i+1] {
c[i] = max(c[i], c[i+1]+1)
}
total += c[i]
}
return total
}