Skip to content

Greedy

Reach for it when the problem says

  • Jump games
  • scheduling
  • "maximum number of…"
Solved
0/31Solved
Problems
31Problems
Variants
7Variants

Problems

7 variants

Running sum and reset

0 of 5 solved

Reach and coverage

0 of 3 solved

Sort then take

0 of 7 solved

Custom sort order

0 of 3 solved

Counters and balance

0 of 3 solved

Local rule scan

0 of 6 solved

Most significant first

0 of 4 solved

Pattern guide

A greedy algorithm makes the choice that looks best right now, commits to it, and never revisits it. When it is correct it is usually the shortest and fastest solution you can write: one sort, one pass, a couple of variables. That is why interviewers love greedy problems, and also why they love asking "how do you know that is right?"

This page is about answering that question. You will learn the seven shapes greedy problems come in, how to recognise each one from the prompt, and the one argument (the exchange argument) that turns a hunch into a proof.

What it is

Greedy works when a local choice can never hurt the final answer. You prove that with an exchange argument: take any optimal answer that disagrees with your greedy choice, swap the greedy choice in, and show the answer is no worse. If that swap always works, greedy is safe. If you can find an input where the swap makes things worse, greedy is wrong and you probably need dynamic programming.

Here is the cleanest example, Jump Game. From index i you may jump up to nums[i] places. Can you reach the end? You never decide which jump to take. You only track reach, the furthest index any visited cell can reach, because the reachable cells always form a prefix.

Jump Game: track the furthest reach
2
0
↑i
3
1
1
2
1
3
4
4
reach = 2

From index 0 you can reach up to index 0 + 2 = 2. Everything in 0..2 is reachable.

1/5

There was no choice to get wrong, because one number summarised every possible path. Most greedy solutions look like this: find the one quantity that summarises everything, then update it in a single pass.

Quick check
What does an exchange argument show?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"maximum number of", "minimum number of"Count-based optimisation. Often take the cheapest or most valuable item first.
"in any order", "you may rearrange"You are free to sort. Sort by the key that makes the swap argument work.
"at most one", "up to k places"A reach or capacity. Track the furthest point or the remaining room.
"as many pieces as possible"Cut as early as you legally can.
"is it possible", "return true if"Often a single running quantity decides it (reach, tank, balance).
"as many times as you like"No limit on actions, so you can grab every small gain.
"largest number", "largest value" with digitsMost significant digit first.

Constraint clues

ConstraintWhat it suggests
n <= 10^5 or moreO(n) or O(n log n). A sort plus a pass is the usual shape.
Values or capacities up to 10^8 or 10^9A DP indexed by value or capacity is too wide. Greedy or sorting it is.
n <= 20 with flips or choicesBrute force over 2^n might pass, but check for a greedy rule on bit weight first.
"O(1) extra space"Two or three running variables, not a table.

Input and output shape clues

  • A list of items, each with a cost and a value, and a limit on how many you take: sort by value and take the best.
  • A sequence you scan once, and the answer is a yes/no or a single number: a running quantity with a reset rule.
  • Pairs of choices per item (city A or B, face up or face down): sort by the difference between the two options.
  • A number or grid of bits to maximise: handle the most significant position first.

Looks like greedy but isn't

  • Coin change with arbitrary coins. "Take the biggest coin" fails for coins [1, 3, 4] and amount 6 (greedy 4+1+1, best 3+3). Use dynamic programming.
  • 0/1 knapsack. "Best value per weight first" fails when items cannot be split. Maximum Units on a Truck is greedy only because every box takes the same single slot.
  • Interval scheduling with weights. Earliest end time is optimal when every meeting counts the same. Once meetings have profits (Maximum Profit in Job Scheduling) you need DP.
  • Longest increasing subsequence. Increasing Triplet is greedy because the length is fixed at three. General LIS needs DP or patience sorting.
Match the pairs0/4 matched

Match each problem to the right tool.

Choose an item, then its match on the other side.

The sub-patterns

Running sum and reset

Use it when you scan a sequence, keep a running total, and the rule is "once the total turns bad, nothing before this point can help". Kadane's algorithm is the template: a negative prefix only drags down what comes next, so drop it.

Gas Station: reset the start when the tank goes negative
-2
0
↑i
-2
1
-2
2
3
3
3
4
tank = -2start = 1

The gains gas[i] - cost[i] for gas [1,2,3,4,5] and cost [3,4,5,1,2]. The tank is negative at once, so start moves to 1.

1/4
Python
def max_sub_array(nums: list[int]) -> int: best = current = nums[0] for num in nums[1:]: current = max(num, current + num) # extend or restart best = max(best, current) return best print(max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Problems: Maximum Subarray, Gas Station, Best Time to Buy and Sell Stock II, Maximum Sum Circular Subarray.

Reach and coverage

Use it when each position extends how far you can get, and you only care about the frontier. Jump Game tracks one reach. Jump Game II tracks the current level's end and the next level's furthest point, which is BFS without a queue. Partition Labels extends a piece to the furthest last occurrence of any letter inside it.

Partition Labels on abcabdde
a
0
↑i
b
1
c
2
a
3
b
4
d
5
d
6
e
7
end = 3

The last a is at index 3, so this piece cannot close before 3.

1/4
Python
def jump(nums: list[int]) -> int: jumps = level_end = furthest = 0 for i in range(len(nums) - 1): furthest = max(furthest, i + nums[i]) if i == level_end: # must jump to go further jumps += 1 level_end = furthest return jumps print(jump([2, 3, 1, 1, 4])) # 2
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Problems: Jump Game, Jump Game II, Partition Labels.

Sort then take

Use it when every item counts the same toward the answer and you must pick some of them under a limit. Sort so the best item is first, then take items until the limit stops you. The swap argument is always the same: if a best answer used a worse item while a better one sat unused, swapping them is no worse.

Assign Cookies after sorting
1
0
↑cookie
1
1
2
2
3
3
greed = [1, 2, 3]happy = 0

Cookies sorted: [1, 1, 2, 3]. Children sorted by greed: [1, 2, 3].

1/4
Python
def max_ice_cream(costs: list[int], coins: int) -> int: bought = 0 for cost in sorted(costs): # cheapest first if cost > coins: break coins -= cost bought += 1 return bought print(max_ice_cream([1, 3, 2, 4, 1], 7)) # 4
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n log n) time for the sort, O(n) space. Problems: Assign Cookies, Maximum Units on a Truck, Hand of Straights, Bag of Tokens, Reduce Array Size to The Half.

Custom sort order

Use it when the answer is an ordering or a split, and the right order is not "by value". Find the key by asking what two neighbours compare on. In Two City Scheduling the key is a - b, the saving from city A. In Largest Number the rule is a + b > b + a as strings. In Queue Reconstruction it is tallest first, then smallest k.

Two City Scheduling: sort by a - b
[10,20]
0
[30,200]
1
[400,50]
2
[30,20]
3

Costs to A and B. Exactly two people must go to each city.

1/4
Python
def two_city_sched_cost(costs: list[list[int]]) -> int: ordered = sorted(costs, key=lambda c: c[0] - c[1]) half = len(costs) // 2 return sum(a for a, _ in ordered[:half]) + sum(b for _, b in ordered[half:]) print(two_city_sched_cost([[10, 20], [30, 200], [400, 50], [30, 20]])) # 110
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n log n) for the sort (Queue Reconstruction adds O(n²) for list inserts). Problems: Two City Scheduling, Largest Number, Queue Reconstruction by Height.

Predict the outputPython

What does this print?

from functools import cmp_to_key
parts = ["3", "30", "34"]
parts.sort(key=cmp_to_key(lambda a, b: -1 if a + b > b + a else 1))
print("".join(parts))
Need a nudge? Hints walk you through it.

Counters and balance

Use it when the state that matters is a count (open brackets, bills in the till), and each character or event moves it up or down. Sometimes the count is a range: in Valid Parenthesis String a * widens the range of possible open counts to low..high.

Valid Parenthesis String on (*))
(
0
↑i
*
1
)
2
)
3
low = 1high = 1

An open bracket: one open, whatever the stars do.

1/4
Python
def min_add_to_make_valid(s: str) -> int: open_count = added = 0 for ch in s: if ch == "(": open_count += 1 elif open_count: open_count -= 1 else: added += 1 # a ")" nothing can ever match return added + open_count print(min_add_to_make_valid("()))((")) # 4
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Problems: Valid Parenthesis String, Minimum Add to Make Parentheses Valid, Lemonade Change.

Local rule scan

Use it when a simple rule at each position, applied left to right (sometimes again right to left), gives the global answer. Plant a flower in the first legal plot. Keep the smallest first and second numbers for an increasing triplet. Count peaks and valleys for a wiggle. Candy uses two passes, one per neighbour rule.

Candy: two passes on ratings [1, 3, 4, 5, 2]
1
0
1
1
1
2
1
3
1
4
ratings = [1, 3, 4, 5, 2]

Everyone starts with one candy.

1/4
Python
def candy(ratings: list[int]) -> int: n = len(ratings) given = [1] * n for i in range(1, n): if ratings[i] > ratings[i - 1]: given[i] = given[i - 1] + 1 for i in range(n - 2, -1, -1): if ratings[i] > ratings[i + 1]: given[i] = max(given[i], given[i + 1] + 1) return sum(given) print(candy([1, 3, 4, 5, 2])) # 11
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) or O(n) space. Problems: Can Place Flowers, Increasing Triplet Subsequence, Wiggle Subsequence, Candy, Merge Triplets to Form Target Triplet.

Most significant first

Use it when the answer is a number built from digits or bits. The leftmost position outweighs everything after it (in binary, 1000 beats 0111), so settle the most significant position first, as well as you can, and only then look at the rest. Broken Calculator is the same idea run backward: from the target, halving is the big move, so take it whenever the number is even.

Score After Flipping Matrix
8421
0011
1010
1100

Each row is a binary number. The first column is worth 8, more than the other three columns together.

1/4
Python
def broken_calc(start_value: int, target: int) -> int: presses = 0 while target > start_value: # work backward from the target target = target + 1 if target % 2 else target // 2 presses += 1 return presses + start_value - target print(broken_calc(3, 10)) # 3
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(digits) or O(log n) for numbers, O(m · n) for a grid. Problems: Maximum Swap, Monotone Increasing Digits, Score After Flipping Matrix, Broken Calculator.

A decision checklist

Go through these questions in order. The first yes usually names the sub-pattern.

Match the pairs0/6 matched

Match the clue to the greedy sub-pattern.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of solving a greedy problem in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Traps

  • Initialising from 0 instead of the first element. Kadane on [-3, -1, -2] must return -1, not 0. Start best and current at nums[0].
  • Stopping one step too late. Jump Game II loops to len(nums) - 2; looping to the end can count an extra jump from the last index.
  • Overwriting instead of taking the max. Candy's second pass must keep max(given[i], given[i + 1] + 1), or it breaks the first pass's rule.
  • Strict versus non-strict comparisons. Increasing Triplet uses <= so equal values never count. Gas Station resets only when the tank goes strictly below 0.
  • Forgetting the all-zero or empty case. Largest Number on [0, 0] must return "0". Bag of Tokens on an empty bag returns 0.
  • Sorting by the obvious key. Largest Number fails with numeric order and with plain string order. Two City Scheduling fails if you sort by a alone.
  • Mutating the caller's input. Can Place Flowers marks plots as it plants. Work on a copy.

Edge cases to always test: one element, all equal, already optimal, strictly increasing and strictly decreasing input, and the smallest input where greedy has a real choice.

Quick check
Your Kadane solution starts with best = 0 and current = 0. Which input breaks it?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
Greedy algorithm
Builds the answer by making the locally best choice at each step and never undoing it.
Exchange argument
A proof that swapping the greedy choice into any optimal answer does not make it worse.
Kadane's algorithm
Maximum subarray in one pass: extend the current run or restart, whichever is larger.
Reach
The furthest index reachable so far. Because reachable cells form a prefix, one number summarises them all.
Custom comparator
A sort rule other than plain value order, such as a + b > b + a for Largest Number.
Most significant first
When building a number, settle the leftmost digit or bit first, since it outweighs everything after it.