Learn / Greedy

Candy and assign cookies

Many greedy problems are solved by sorting and then matching or sweeping: smallest cookie that satisfies the least greedy child, change kept for later customers, the biggest values given the biggest weights. The skill is spotting the order that makes a local choice safe, and checking it with a swap argument or a small brute force.

How to recognise it

  • A short array, and sorting it seems to make the choice obvious.
  • Pairing items from two lists.
  • Ratings, neighbours or prefix totals with a simple local rule.

How to find the greedy order

  1. Try sorting by the obvious key (size, value, end time, ratio).
  2. Look for a swap argument: if two neighbouring items are "out of order", does swapping them never hurt?
  3. Check the rule against a brute force on small inputs. This guide's tests do exactly that.

Patterns in this section

IdeaProblems
sort both lists and matchassign cookies, pairs of two arrays
biggest values get the biggest weightssum of arr[i] × i, maximum product subset
interleave small and largemaximum circular sum of differences
keep the most flexible resourcelemonade change
two passescandy
running totalwine trading, three stacks, picking up chicks
take the biggest piece firstcoins, smallest subset with a larger sum, k-centres

Proving it

A greedy is only right when the choice it makes now can always be part of some best answer. The swap argument shows this: take any best answer, change it to agree with the greedy choice, and show it is still at least as good.

Common mistakes

  • Trusting a greedy without a small brute-force check.
  • Missing edge cases such as zeros, negatives or a single item.

Problems

0 of 24 solved

Check yourself

Children greed [1, 2, 3], cookies [1, 1]. How many children are happy?

To pair two lists so the sum of differences is smallest, how do you pair?

For Candy, why do two passes, left then right, suffice?

Paying with a 20 at a lemonade stand, which change should you give if you can?