Greedy
A greedy algorithm builds an answer by taking the locally best choice at each step and never revising it. It is fast when a proof says those choices stay optimal. It is wrong when they do not.
Detailed Explanation
DP considers many sub-answers. Greedy commits. Interval scheduling is the usual safe example: always take the remaining meeting that finishes first. You can prove any optimal set can be rewritten to include that meeting (exchange argument). Huffman coding and Kruskal's MST are other cases with proofs.
The danger is that many problems look greedy and are not. Coin change with denominations {1, 3, 4} and amount 6 is greedy-wrong if you always take 4 (4+1+1 vs 3+3). 0/1 knapsack by value/weight ratio fails. You need either a known pattern or a short proof.
When greedy is correct, you often sort, then scan once. That is O(n log n). When it is not, the same sort-and-scan produces a plausible, wrong answer. Interviewers look for you to name the invariant or the exchange, not only the code.
You reach for greedy when the problem matches a known template: earliest finish, jump game (farthest reachable), minimum platforms, activity selection, Dijkstra's "closest unsettled node" (greedy + proof on non-negative weights). You reach for DP when subproblems overlap and local choice is unsafe. You reach for backtracking when you must enumerate.
The cost of a missing proof is a green sample and a red hidden test. The cost of sorting the wrong key (start time instead of finish time) is the same. Write the comparison explicitly. Handle ties. Watch overflow when you accumulate (long for sums of int).
Greedy plus a data structure is still greedy: a PriorityQueue of next-best edges (Kruskal uses a sorted list plus union-find; Prim uses a heap). The heap does not make it DP.
Code Examples
import java.util.Arrays;
import java.util.Comparator;
public class Meetings {
static int maxMeetings(int[][] intervals) {
Arrays.sort(intervals, Comparator.comparingInt(a -> a[1])); // earliest finish
int taken = 0;
int end = Integer.MIN_VALUE;
for (int[] slot : intervals) {
if (slot[0] >= end) {
taken++;
end = slot[1];
}
}
return taken;
}
public static void main(String[] args) {
int[][] slots = {{1, 3}, {2, 4}, {3, 5}};
System.out.println(maxMeetings(slots)); // prints: 2
}
}public class Jump {
static boolean canJump(int[] nums) {
int far = 0;
for (int i = 0; i < nums.length; i++) {
if (i > far) {
return false;
}
far = Math.max(far, i + nums[i]);
}
return true;
}
public static void main(String[] args) {
System.out.println(canJump(new int[] {2, 3, 1, 1, 4})); // prints: true
System.out.println(canJump(new int[] {3, 2, 1, 0, 4})); // prints: false
}
}Common Gotchas
A working example is not a proof
coin systems and knapsack look greedy and fail.
Sorting by the wrong key
earliest start is not earliest finish.
Dijkstra is greedy and requires non-negative weights
negative edges need other algorithms.
Overflow in accumulated greedy sums
use `long`.