Lesson 145 of 296
Greedy algorithms
What you will learn
- What a greedy algorithm is
- When greedy works and when it fails
- Jump Game and Jump Game II
- Maximum Subarray (Kadane's algorithm)
- Gas Station
- How to justify a greedy choice
On this page
What is greedy?
A greedy algorithm makes the choice that looks best right now at each step, and never goes back. It is usually simple and fast (often O(n) or O(n log n)).
The catch: greedy only works when local best choices lead to the global best answer. You must be able to explain why the greedy choice is safe.
Where greedy fails: making change for 6 with coins [1, 3, 4]. Greedy takes the largest coin first: 4 + 1 + 1 = 3 coins. The best is 3 + 3 = 2 coins. That problem needs dynamic programming (Lesson 146).
Jump Game
Problem (LeetCode 55): nums[i] is the maximum jump length from position i. Starting at 0, can you reach the last index?[2, 3, 1, 1, 4] → true. [3, 2, 1, 0, 4] → false.
Greedy: track the furthest index reachable so far. If you ever stand on an index beyond it, you are stuck.
function canJump(nums: number[]): boolean {
let furthest = 0;
for (let i = 0; i < nums.length; i++) {
if (i > furthest) return false;
furthest = Math.max(furthest, i + nums[i]!);
}
return true;
}O(n) time, O(1) space.
Jump Game II
Problem (LeetCode 45): the minimum number of jumps to reach the end (always possible).
Greedy by levels (like BFS): everything reachable with jumps jumps forms a range. While scanning that range, record the furthest point the next jump can reach. When you reach the end of the current range, you must jump.
function jumpGameII(nums: number[]): number {
let jumps = 0;
let currentEnd = 0;
let furthest = 0;
for (let i = 0; i < nums.length - 1; i++) {
furthest = Math.max(furthest, i + nums[i]!);
if (i === currentEnd) {
jumps++;
currentEnd = furthest;
}
}
return jumps;
}O(n).
Maximum Subarray (Kadane's algorithm)
Problem (LeetCode 53): the largest sum of any contiguous subarray.[-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6 ([4, -1, 2, 1]).
Idea: walk through the array keeping the best sum of a subarray ending here. If the running sum becomes negative, it can only hurt what comes next, so start fresh.
function maxSubArray(nums: number[]): number {
let best = nums[0]!;
let current = 0;
for (const n of nums) {
current = Math.max(n, current + n);
best = Math.max(best, current);
}
return best;
}current = max(n, current + n) means "either extend the previous subarray, or start a new one at n". Starting best at nums[0] handles arrays where every number is negative. O(n) time, O(1) space. (Kadane's algorithm is also a simple form of dynamic programming.)
Gas Station
Problem (LeetCode 134): gas stations on a circle. gas[i] is fuel available at station i, cost[i] is fuel needed to reach the next one. Find the starting station from which you can drive all the way round, or -1.
Two facts:
- If total gas is less than total cost, it is impossible.
- If you start at A and first run out of fuel before reaching B, then no station between A and B can be the start either (they would arrive with even less fuel). So jump the start to B.
function canCompleteCircuit(gas: number[], cost: number[]): number {
let total = 0;
let tank = 0;
let start = 0;
for (let i = 0; i < gas.length; i++) {
const gain = gas[i]! - cost[i]!;
total += gain;
tank += gain;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total >= 0 ? start : -1;
}O(n).
How to justify a greedy choice
Interviewers will ask "why is that correct?". Common arguments:
- Exchange argument: if a best solution did something different, you could swap in the greedy choice without making it worse (used for activity selection, Lesson 144).
- Staying ahead: after every step, the greedy solution is at least as good as any other (Jump Game's furthest reach).
- Counter-example search: try small cases where greedy might fail (like the coins example). If you find one, switch to dynamic programming.
How to say it in an interview
"A greedy algorithm makes the locally best choice at each step without reconsidering. It is fast but only correct when local choices lead to a global optimum, so I justify it with an exchange or stays-ahead argument, or look for counter-examples. Jump Game tracks the furthest reachable index; Jump Game II counts levels of reach like BFS; Kadane's algorithm extends or restarts a running sum; Gas Station resets the start whenever the tank goes negative. When greedy fails, like coin change with arbitrary coins, I use dynamic programming."
Key words
| Word | Meaning |
|---|---|
| Greedy algorithm | Choosing the best-looking option at each step |
| Local / global optimum | Best at one step / best overall |
| Kadane's algorithm | Maximum subarray sum in O(n) |
| Exchange argument | A proof that swapping in the greedy choice is never worse |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.