Candy

Each child gets at least one candy; higher-rated child gets more than smaller-rated neighbors. Minimum candies via two passes.

Hard
Time O(n) Space O(n)
LeetCode
4 min read
greedy array

Problem#

Each child gets at least 1 candy. A child with a higher rating than an adjacent child must get more candy. Return the minimum total candies.

Examples#

  • [1,0,2]5 ([2,1,2])
  • [1,2,2]4 ([1,2,1])

Constraints#

  • 1 <= n <= 2 * 10^4.

Hints#

Hint 1
Two passes: left-to-right enforces “right > left” constraints; right-to-left enforces “left > right”. Take max at each index.

Approach#

Two passes. Initialize all to 1. Left pass: if ratings[i] > ratings[i-1], candy[i] = candy[i-1] + 1. Right pass: if ratings[i] > ratings[i+1], candy[i] = max(candy[i], candy[i+1] + 1).

Solution#

Candy
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> c(n, 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] = max(c[i], c[i + 1] + 1);
return accumulate(c.begin(), c.end(), 0);
}
};

Editorial#

Each constraint (“more than left neighbor”, “more than right neighbor”) creates a directional requirement. Two opposite-direction passes satisfy each independently; taking the max at each index satisfies both. Equal ratings impose no constraint, so the runs reset.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.