CSE 565: Greedy Algorithms Practice Problems
1. Given a set X = {x1, x2, . . ., xn} of points on the real line, the task here is to come up with a greedy
algorithm that finds the smallest possible set of intervals, each of length 2, that contains all the given
points.
1.1) Pseudo Code for the greedy algorithm (Assumption here is that the intervals are sorted in an
increasing order)
1. Let n <- length of X (points array)
2. Initialize intervals<- []
3. Let start = X [0] and end = X [0] + 2
4. Add {start, end} to intervals
5. Let i <- 1
6. Loop until i<n:
6.1. If X [i] > end:
6.1.1. Set start <- X [i], end <- X [i] + 2
6.1.2. Add {start, end} to intervals
6.2. Increment i
7. Return intervals
Implementing the above pseudo code on the given example X = {1.5, 2.0, 2.1, 5.7, 8.8, 9.1, 10.2}, gave
the following output set of intervals.
[{1.5 3.5}, {5.7 7.7}, {8.8 10.8}]
1.2) Proof of correctness:
Assume the interval set produced by the greedy algorithm is not optimal. We try to prove the
correctness of the algorithm the same way we proved it for the greedy scheduling algorithm.
Let i1, i2, i3 … in be the set of intervals produced by our greedy algorithm, and let j1, j2, j3 ...jm be an optimal
set of intervals that covers all the points in X with the fewest number of intervals. We want to show that
k=m here.
Let i be an interval in the Solution S* obtained by Greedy Let S be the optimal solution Let k be the last
interval in S. Assume that all intervals are matched exact in both greedy and optimal until (i,k) in S* and
S By Induction, we can say that S* {i+1} <= S{k+1}-2 But, If Both could fit in same interval of size 2, they
can be interchanged easily. S* {i+1} can be replaced with S {K+1}, which means I = k So, the Solution in
the greedy is optimal.