Skip to main content

Greedy

A greedy algorithm takes the choice that looks best right now and never undoes it. That is only correct when you can show the choice is safe:

  • Exchange argument: take any optimal answer that disagrees with the greedy choice. Swap the greedy choice in. If the answer stays legal and no worse, greedy never loses.
  • Stays ahead: after every step, the greedy partial answer is at least as good as any other partial answer of the same length.

If neither argument works, the problem is usually dynamic programming: the best move now depends on what comes later.

How to spot it​

  • The problem asks for a minimum, a maximum, or "is it possible".
  • One local rule decides each step: earliest, smallest, largest, as soon as possible.
  • Taking that choice never closes off an option you would have needed later.

Before trusting the rule, try three or four tiny inputs and look for one where the best-now choice loses. One counterexample kills it.

Commit on the scan​

Decide each element once, left to right. The decision is the earliest or cheapest one that keeps the rest of the input legal, so nothing behind the scan ever needs revisiting.

605. Can Place Flowers​

605. Can Place Flowers

LeetCode
Easy

Greedy Scan

FIG. 605 CAN PLACE FLOWERS● INTERACTIVE
visualization loads as you reach it
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
size = len(flowerbed)
for i in range(size):
if flowerbed[i] == 0:
empty_left = (i == 0) or (flowerbed[i - 1] == 0)
empty_right = (i == size - 1) or (flowerbed[i + 1] == 0)
if empty_right and empty_left:
flowerbed[i] = 1
n -= 1
return n <= 0
top ↑

1827. Minimum Operations to Make the Array Increasing​

1827. Minimum Operations to Make the Array Increasing

LeetCode
Easy

Greedy Scan

FIG. 1827 MINIMUM OPERATIONS TO MAKE THE ARRAY INCREASING● INTERACTIVE
visualization loads as you reach it
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
for i in range(1, len(nums)):
if nums[i] <= nums[i - 1]:
diff = nums[i - 1] - nums[i] + 1
ans += diff
nums[i] += diff
return ans
top ↑

2259. Remove Digit From Number to Maximize Result​

2259. Remove Digit From Number to Maximize Result

LeetCode
Easy

Greedy Scan

FIG. 2259 REMOVE DIGIT FROM NUMBER TO MAXIMIZE RESULT● INTERACTIVE
visualization loads as you reach it
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
n = len(number)
last_occ = 0
for i in range(n - 1):
if number[i] == digit:
if number[i + 1] > digit:
return number[:i] + number[i + 1 :]
last_occ = i
if number[-1] == digit:
last_occ = n - 1
return number[:last_occ] + number[last_occ + 1 :]
top ↑

392. Is Subsequence​

392. Is Subsequence

LeetCode
Easy

Greedy Match

FIG. 392 IS SUBSEQUENCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
m, n = map(len, (s, t))
a = b = 0
while a < m and b < n:
if s[a] == t[b]:
a += 1
b += 1
return a == m
top ↑

Count, then pick the cheaper side​

Free moves collapse the input into a few groups. Count each group, then pay only for the smaller one.

1217. Minimum Cost to Move Chips to The Same Position​

1217. Minimum Cost to Move Chips to The Same Position

LeetCode
Easy

Count Parities

FIG. 1217 MINIMUM COST TO MOVE CHIPS TO THE SAME POSITION● INTERACTIVE
visualization loads as you reach it
class Solution:
def minCostToMoveChips(self, position: list[int]) -> int:
on_odds = on_evens = 0
for pos in position:
on_odds += pos % 2
on_evens += pos % 2 == 0
return min(on_odds, on_evens)
top ↑

Greedy elsewhere​

These problems are greedy too, but another technique carries most of the work, so they live with that technique:

When greedy fails​

Coins {1, 3, 4}, amount 6. Largest-coin-first takes 4 + 1 + 1, three coins. The best answer is 3 + 3, two coins. Taking the 4 left a remainder only small coins could fill, so the right choice depends on what is left. That is the signal to switch to dynamic programming.