Video in progress
When does a greedy algorithm give the right answer, and how do you justify it in an interview? Show it with "jump game".
Greedy makes the locally best choice at each step and never goes back. It is correct only when the "greedy choice property" holds: an optimal solution that includes the local choice always exists. I justify it with an exchange argument, or I test it by looking for a small counterexample.
📖 Answer
Jump game: a[i] is the maximum number of steps you can jump from cell i. Can you reach the last cell?
With DP it's O(n²): for each cell, "can I reach the end from here". With greedy it's O(n): we keep the farthest point reachable so far.
static boolean canReach(int[] a) {
int far = 0;
for (int i = 0; i < a.length; i++) {
if (i > far) return false; // this cell can't be reached at all
far = Math.max(far, i + a[i]);
if (far >= a.length - 1) return true;
}
return true;
}
Why is it correct? Every cell up to far is reachable, so the range is continuous. That means it doesn't matter which cell we jumped from, only the farthest one matters. Greedy loses no information.
A case where greedy misleads you: in 0/1 knapsack, "take the item with the highest value/weight ratio". The capacity is 50, and the items are (10 kg, 60), (20 kg, 100), (30 kg, 120). By ratio you take the first two: 160. The optimum is the second and third: 220. In fractional (divisible) knapsack, though, the same greedy is correct.
In an interview I go about it this way:
- I say the greedy idea out loud.
- I look for 2-3 small counterexamples; if I find one, I switch to DP.
- If I don't, an exchange argument: "if the optimal solution makes a different choice, swapping in my choice doesn't make the result worse".
Classics where greedy works: choosing non-overlapping intervals by end time, Huffman coding, Dijkstra with no negative edges, Kruskal.
Sign up to mark studied questions and save your progress.