Lecture 2
Lecture 2
• Euler Theorem
03/04/2025 Page 1
Week 2: Greedy Algorithms
03/04/2025 Page 2
Greedy Algorithm
• A technique to solve problems:
– always makes the locally best choice at the moment
(local optimal).
– Hopefully, a series of locally best choices will lead to a
globally best solution.
• Greedy algorithms yield optimal solutions for
many (but not all) problems.
• Selecting jobs:
– (3, 4),
– (4, 5),
– (5, 6),
– (7, 9),
A
for j = 1 to n {
if (job j compatible with A)
A A {j}
}
return A
G: i1 i1 ir ir+1
A: i1 i1 ir ir+1
Page 14
Another Proof for Interval Scheduling: (words without figures, expected in exams)
Let: be the solution return by greedy
Let : be an optimal solution
Both are in the order of finish time.
1. If since finishes the earliest according to our algorithm, thus finishes not
later than we can replace by in Opt. After this replacement, Opt’: is still
optimal. Now set
.
2. If earlier than set
…….
After a number of replacements:
Or
The last case is impossible, since according to our algorithm, no job starts later than the
finish time of
Therefore, G is optimal ( it have the same number of jobs as Opt)
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B
0 1 2 3 4 5 6 7 8 9 10 11 Page 16
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B C
0 1 2 3 4 5 6 7 8 9 10 11 Page 17
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
BA
0 1 2 3 4 5 6 7 8 9 10 11 Page 18
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B E
0 1 2 3 4 5 6 7 8 9 10 11 Page 19
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B D
E
0 1 2 3 4 5 6 7 8 9 10 11 Page 20
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B E F
0 1 2 3 4 5 6 7 8 9 10 11 Page 21
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B E G
0 1 2 3 4 5 6 7 8 9 10 11 Page 22
Interval Scheduling
B
C
A
E
D
F
G
H Time
0 1 2 3 4 5 6 7 8 9 10 11
B E H
0 1 2 3 4 5 6 7 8 9 10 11 Page 23
Interval Partitioning
Interval Partitioning
• Interval partitioning.
– Lecture j starts at sj and finishes at fj.
– Goal: find minimum number of classrooms to schedule all
lectures so that no two lectures occur at the same time in
the same room.
e j
c d g
b h
a f i
c d f j
b g i
a e h
c d f j
b g i
a e h
Page 28
Greedy Algorithm:
c d g j
b f i
Depth:aThe maximum No.e of jobs required at
h any time.
Depth
:3