Greedy Algorithms8 sections · 316 units
Open in Course

Candy - Algorithm

Two-pass greedy

Pass 11 (left to right): If rating[i] > rating[i-1], give candy[i] = candy[i-1] + 11. Pass 22 (right to left): If rating[i] > rating[i+1] and candy[i] <= candy[i+1], give candy[i] = candy[i+1] + 11.

This handles both directions. Each pass ensures one direction of the constraint. Time: O(n)O(n). Space: O(n)O(n). Common bug: using only one pass and missing valleys where you need more candies from the right.