Greedy Algorithms

5 min readMake locally optimal choices at each stage.

Greedy Algorithms

A Greedy Algorithm makes the locally optimal choice at each step and never revisits past decisions. Unlike DP, it does not explore all possibilities — it commits immediately. Greedy works when local optimality guarantees global optimality.


Problem: Best Time to Buy and Sell Stock

Given daily prices, find the maximum profit from one buy-sell transaction.

Greedy insight: buy at the lowest price seen so far, and at each day compute the profit if we sell today.

def max_profit(prices: list[int]) -> int: min_price = float('inf') max_profit = 0 for price in prices: min_price = min(min_price, price) # update running minimum max_profit = max(max_profit, price - min_price) # best profit so far return max_profit

One pass, O(N)O(N) time. No DP table needed because the greedy choice (track the minimum) is always correct.


Problem: Jump Game

Given an array where each element is the maximum jump length from that position, can you reach the last index?

Greedy insight: track the furthest reachable position. If you can reach i, you can reach everything up to i + nums[i].

def can_jump(nums: list[int]) -> bool: max_reach = 0 for i, jump in enumerate(nums): if i > max_reach: return False # i is unreachable max_reach = max(max_reach, i + jump) return True

Greedy vs. Dynamic Programming

GreedyDynamic Programming
Decision makingCommit to the best current optionExplore all options, pick the best
CorrectnessOnly works when local opt = global optAlways correct (for DP-solvable problems)
SpeedUsually O(N)O(N) or O(NlogN)O(N \log N)Often O(N2)O(N^2) or O(NK)O(N \cdot K)
When to useExchange argument or matroid structureOverlapping subproblems

Proving Greedy Correctness

Before coding a greedy solution, convince yourself it works with an exchange argument:

Suppose the optimal solution makes a different choice at step kk. Show that swapping its choice for the greedy choice produces a solution that is at least as good.

If you can make that argument, greedy is correct.


When Do I Use This?

  • Problems with interval scheduling, minimum spanning trees, or Huffman encoding.
  • Keywords: "minimum", "maximum", "feasible", and the constraint structure is simple enough that local choices dominate.
  • When DP would work but seems unnecessarily complex — check if greedy suffices.

Practice Problems

How helpful was this content?

Comments

0/2000

Sign in to join the discussion