Greedy Algorithms
A greedy algorithm (English: greedy algorithm), also known as a greedy method, is an algorithmic strategy that makes the best or optimal (i.e., most favorable) choice at each step in the current state, hoping to lead to a globally best or optimal result.
Greedy Algorithms It is like what we often call focusing only on immediate gains without considering overall optimality; the choices made are only locally optimal in some sense.
Imagine a pile of coins of different denominations (such as 1 yuan, 5 jiao, 1 jiao) in front of you, and you need to use the fewest coins to make 1.8 yuan.
A very natural idea is:always take the coin with the largest denomination first。
First take 1 yuan, leaving 0.8 yuan; then take 5 jiao, leaving 0.3 yuan; finally take three 1-jiao coins.
Throughout the process, at every step we made the choice that seemed best at the moment, and this is the core idea of the greedy algorithm.
Greedy AlgorithmsIt is like a short-sighted but decisive person:
- Choice at each step: make the choice that seems optimal in the current state
- Ignore the overall picture: do not consider the future impact of this choice
- Expected result: hope that locally optimal choices lead to a globally optimal solution
Real-life examples:
- Giving change: always use the largest denomination coin first
- Mountain climbing: always move in the steepest direction
- Shopping: always buy the item with the best current deal
- Route selection: always choose the currently shortest route
Characteristics of Greedy Algorithms
- Greedy choice property: the optimal choice at each step can be derived from the locally optimal choices of previous steps. Later choices do not affect earlier ones.
- Optimal substructure: the optimal solution of a problem contains the optimal solutions of its subproblems. This is a property shared with dynamic programming, but a greedy algorithm "greedily" picks the optimal solution of the subproblem at every step.
| Feature | Description | Advantages | Disadvantages |
|---|---|---|---|
| Local optimum | Choose the currently optimal solution at each step | Simple and intuitive | May not be globally optimal |
| Irreversible | Cannot go back after a choice is made | Fast decisions | Can easily get stuck in a local optimum |
| Efficiency | Usually low time complexity | Highly practical | Limited scope of application |
| Simple implementation | Clear and easy-to-understand logic | Easy to code | Requires proof of correctness |
Difference from Dynamic Programming
This is a point beginners often confuse. Let's compare with a table:
| Feature | Greedy Algorithms | Dynamic Programming |
|---|---|---|
| Decision basis | Makes the currently optimal choice at every step,No backtracking。 | Each step's choice depends on subproblem solutions; intermediate results are stored and multiple options can be compared. |
| Optimality guarantee | Not guaranteed to reach a global optimum; the problem itself must have the greedy choice property. | Usually reaches a global optimum. |
| Efficiency | Efficient, usually with lower time complexity. | Relatively lower, because overlapping subproblems must be solved. |
| Applicable scenarios | Problems with the greedy choice property and optimal substructure, such as Huffman coding and minimum spanning trees. | Problems with optimal substructure and overlapping subproblems, such as the knapsack problem and shortest paths. |
Simply put,Dynamic programming is "plan before acting", sacrificing the present for long-term gain; the greedy algorithm is "living for today", pursuing only immediate benefits.
Basic Framework of Greedy Algorithms
Greedy algorithms have no fixed code template, but their idea can be summarized in the following steps:
- Build a mathematical model: abstract the real problem into a mathematical one.
- Define the greedy strategy: determine the criterion for choosing the "optimal solution" at each step. This is the core and the difficult part of the algorithm.
- Prove the greedy strategy: prove that the defined greedy strategy leads to a global optimum (optional but important; for algorithm problems, understanding its correctness is usually required).
- Iterative solving: following the strategy, make greedy choices step by step from the initial state until the problem is solved.
A general pseudocode framework is as follows:
Example
def
greedy_algorithm
(
problem
)
:
1. Initialization: may include sorting, creating result containers, etc.
solution
=
[
]
2. Iterate over all options, usually after sorting by some rule
for
item
in
sorted
(
problem.
items
,
key
=
Greedy strategy rule
)
:
3. Greedy choice: if the current option satisfies the condition, adopt it
if
is_feasible
(
solution
,
item
)
:
solution.
append
(
item
)
4. Return the final constructed solution
return
solution
Classic Problems and Code Examples
Let's experience the application of greedy algorithms through several classic problems. For each problem we will: 1) analyze the problem and greedy strategy; 2) provide complete code; 3) explain it line by line.
Example 1: Coin Change Problem (Coin Change)
Description: suppose the coin system is [100, 50, 20, 10, 5, 1] (unit: fen), and we need to give change of amount fen; find the minimum number of coins to use.
Greedy strategy:Each time choose the largest coin whose value does not exceed the remaining amount. For the RMB system, this strategy is effective.
Code Implementation:
Example
def
coin_change_greedy
(
coins
,
amount
)
:
"""
Solve the coin change problem with a greedy algorithm (for a specific coin system)
:param coins: list[int], list of coin denominations, should be sorted in descending order
:param amount: int, total amount to give change for
:return: list[int], list of coin denominations used
"""
coins.
sort
(
reverse
=
True
)
Ensure coins are sorted by denomination from largest to smallest
result
=
[
]
Used to store the change coins
remaining
=
amount
The remaining amount to give change for
for
coin
in
coins:
When the current coin value is no more than the remaining amount, use as many of it as possible
while
remaining
=
coin:
result.
append
(
coin
)
remaining -
=
coin
Deduct the current coin value from the remaining amount
Check whether the change is exactly made
if
remaining
==
0
:
return
result
else
:
For cases where exact change cannot be made (though this won't happen with this coin system)
return
None
Test Data
test_coins
=
[
100
,
50
,
20
,
10
,
5
,
1
]
test_amount
=
186
1 yuan 8 jiao 6 fen
change
=
coin_change_greedy
(
test_coins
,
test_amount
)
(
f
"Change for {test_amount} fen requires coins: {change}"
)
(
f
"Number of coins: {len(change)}"
)
Output: change for 186 fen requires coins: [100, 50, 20, 10, 5, 1]
Number of coins: 6
Code Analysis:
- Line 8:
coins.sort(reverse=True)is key preparation for the greedy strategy, ensuring we always consider large-denomination coins first. - Lines 12-15:
whileThe loop ensures we keep using the current coin as long as possible, implementing the "as many as possible" greedy choice. - Lines 18-22: check the final result to ensure the amount matches exactly.
Important reminder: the greedy algorithm for the coin change problem does not always give the optimal solution! For example, if the coin system is [25, 20, 10, 5, 1] and we need to make 40 fen, the greedy approach chooses 25+10+5 (three coins), but the optimal solution is 20+20 (two coins).The greedy strategy works only for specific currency systems (such as RMB).
Example 2: Interval Scheduling Problem (Interval Scheduling)
Description: given many meetings (each with a start and end time), how should you schedule them to maximize the number of meetings held in one room?
Greedy strategy:Each time choose the meeting that ends earliest. This leaves more time for later meetings.
Code Implementation:
Example
def
interval_scheduling
(
intervals
)
:
"""
Solve the maximum non-overlapping interval problem (interval scheduling)
:param intervals: list of [start, end], list of intervals
:return: list of [start, end], list of selected intervals
"""
1. Sort by end time in ascending order
intervals_sorted
=
sorted
(
intervals
,
key
=
lambda
x: x
[
1
]
)
selected
=
[
]
Store the selected intervals
last_end_time
=
float
(
'inf'
)
Initialize the end time of the last selected interval
for
interval
in
intervals_sorted:
start
,
end
=
interval
2. Greedy choice: if the current interval's start time is not earlier than the last selected interval's end time, select it
if
start
=
last_end_time:
selected.
append
(
interval
)
last_end_time
=
end
Update the last end time
return
selected
Test data: each sublist represents a meeting [start time, end time]
test_intervals
=
[
[
1
,
3
]
,
[
2
,
4
]
,
[
3
,
5
]
,
[
4
,
6
]
,
[
5
,
7
]
,
[
1
,
2
]
,
[
2
,
3
]
,
[
1
,
4
]
]
result
=
interval_scheduling
(
test_intervals
)
(
"Maximum meetings that can be scheduled (after sorting by end time):"
)
for
meeting
in
result:
(
f
" Meeting [{meeting[0]}, {meeting[1]}]"
)
(
f
"Total {len(result)} meetings"
)
One possible output (the order may differ after sorting, but the count is optimal):
Meeting [1, 2]
Meeting [2, 3]
Meeting [3, 5] or [4, 6], etc.
Total 4 meetings
Code Analysis:
- Line 10:
sorted(intervals, key=lambda x: x[1])is the core of implementing the greedy strategy, sorting by end time. - Lines 16-19:
if start >= last_end_timeis the feasibility check, ensuring the current meeting does not overlap with already selected meetings. - The time complexity of this algorithm is O(n log n), mainly from the sorting.
Example 3: Huffman Coding - Concepts and Simplified Implementation
Huffman coding is a greedy algorithm used for lossless data compression. Its core idea is:assign shorter codes to characters with high frequency and longer codes to characters with low frequency。
Greedy strategy: repeatedly merge the two nodes with the smallest frequencies to build a binary tree.
Since the full implementation is long, here we show its core greedy merging process:
Example
import
heapq
class
Node:
"""Node class for the Huffman tree"""
def
init
(
self
,
char
,
freq
)
:
self
.
char
=
char
character (only leaf nodes have it)
self
.
freq
=
freq
Frequency
self
.
left
=
None
self
.
right
=
None
define comparison methods so nodes can be compared in the heap
def
lt
(
self
,
other
)
:
return
self
.
freq
<
other.
freq
def
build_huffman_tree
(
char_freq
)
:
"""
Build the Huffman tree
:param char_freq: dict, characters and their frequencies, e.g. {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45}
:return: Node, the root node of the Huffman tree
"""
1. Initialization: create a leaf node for each character and put it into a min-heap (priority queue)
heap
=
[
Node
(
char
,
freq
)
for
char
,
freq
in
char_freq.
items
(
)
]
heapq
.
heapify
(
heap
)
Transform the list into a min-heap
2. Greedy merging: while there is more than one node in the heap
while
len
(
heap
)
1
:
pop the two nodes with the smallest frequencies
left
=
heapq
.
heappop
(
heap
)
right
=
heapq
.
heappop
(
heap
)
create a new internal node whose frequency is the sum of the children's frequencies
merged
=
Node
(
None
,
left.
freq
- right.
freq
)
merged.
left
=
left
merged.
right
=
right
push the new node back into the heap
heapq
.
heappush
(
heap
,
merged
)
the last node remaining in the heap is the root of the Huffman tree
return
heap
[
0
]
if
heap
else
None
Test Data
test_freq
=
{
'a'
:
5
,
'b'
:
9
,
'c'
:
12
,
'd'
:
13
,
'e'
:
16
,
'f'
:
45
}
root
=
build_huffman_tree
(
test_freq
)
(
"Huffman tree construction complete! Root node frequency ="
,
root.
freq
if
root
else
0
)
Output: Huffman tree construction complete! Root node frequency = 100
Algorithm visualization: The figure below shows the first few merging steps of building the Huffman tree with the test data above:

Diagram explanation: The algorithm always selects the two nodes with the smallest frequencies from all available nodes (initially leaf nodes, later including internal nodes) and merges them to create a new internal node. This process repeats until a complete binary tree is formed. The leaf nodes of this tree correspond to the original characters, and the path from the root to a leaf (left branch = 0, right branch = 1) is the Huffman code for that character.
Correctness Proof of Greedy Algorithms
How do you determine whether a problem can be solved with a greedy algorithm? Usually you need to prove the following two points:
- Greedy choice property: Use mathematical induction or proof by contradiction to show that the optimal choice of the first step is contained in some globally optimal solution.
- Optimal substructure: prove that after making the first greedy choice, the original problem is reduced to a smaller subproblem of the same type。
Starts with the interval scheduling problem as an example, the proof idea:
- Greedy choice: Let the interval with the earliest end time among all intervals be
i. There exists an optimal solution that contains the intervali。 - Proof: Suppose some optimal solution does not contain
i. Let the first interval in that optimal solution bej. Becauseiends the earliest, so replacing itiReplacementjwill not conflict with other intervals, and the size of the solution is unchanged, so a solution that containsiit is also an optimal solution.
- Optimal substructure: After selecting the interval
i, the remaining problem is to find an optimal solution among all intervals that do notioverlap with it. This forms a subproblem of the original problem.
Practical Exercise
Now, try using a greedy algorithm to solve the following problems to reinforce your understanding.
Exercise 1: Jump Game
Problem: Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents the maximum length you can jump from that position. Determine whether you can reach the last index. Example:nums = [2,3,1,1,4], return True(jump 1 step from index 0 to index 1, then jump 3 steps to the last index). Greedy strategy hint: instead of simulating how far you jump at each step, maintain a farthest reachable position。
Exercise 2: Assign Cookies
Problem: There is a group of children and a pile of cookies, each child has a greed factor g[i], and each cookie has a size s[j]. A child is content only when the cookie size >= the child's greed factor. Find the maximum number of children that can be content. Example:g = [1,2,3], s = [1,1], output 1。 Greedy strategy hint: to satisfy more children,you should use the smallest cookie to satisfy the child with the smallest greed factor(or think about it the other way around).
Exercise 3: Best Time to Buy and Sell Stock II
Problem: Given an array prices, where prices[i] is the price of a given stock on day i . You may complete as many transactions as you like (i.e., buy and sell one share of the stock), but you cannot engage in multiple transactions at the same time (you must sell the previous stock before buying again). Compute the maximum profit you can achieve. Example:prices = [7,1,5,3,6,4], output 7(buy at 1 and sell at 5, profit 4; buy at 3 and sell at 6, profit 3; total profit 7). Greedy strategy hint: Profit can be decomposed into daily price differences. As long as today's price is higher than yesterday's, count that difference as profit。