Algos HW4
Algos HW4
a) Create a list of interval endpoints, pairing each endpoint with a flag to indicate
whether it's a left endpoint or a right endpoint.
b) Sort these endpoints in ascending order.
c) Initialize an empty set `Y` to store the intervals that will constitute the smallest
cover.
d) Iterate through the sorted endpoints:
i) - For each endpoint:
ii) - If it's a left endpoint and it's not covered by any interval in `Y`, add the
corresponding interval to `Y`.
iii) - If it's a right endpoint and it covers an interval in `Y`, remove that interval
from `Y`.
e) The set `Y` will contain the smallest cover for the given set of intervals.
f) The time complexity of this algorithm is O(n log n).
g) The correctness of the proof:
i) Can be proved through contradiction
(1) Suppose there exists an optimal solution where the algorithm's
choice at some step is not the rightmost endpoint. If we replace
this choice with the rightmost endpoint, it will either maintain or
decrease the size of the cover since the replaced interval covers
the same points as the previous one and possibly more.
Therefore, the greedy algorithm's choice of selecting the rightmost
endpoint at each step ensures that it constructs the smallest
cover.
total_mismatch = 0
for i in range(len(jobs)):
min_mismatch = float('inf')
min_idx = -1
for j in range(len(machines)):
mismatch = abs(jobs[i] - machines[j])
if mismatch < min_mismatch:
min_mismatch = mismatch
min_idx = j
total_mismatch += min_mismatch
del machines[min_idx]
4b) If c [i] = b^(i- 1) for some integer b ≥ 2: The greedy algorithm of always subtracting the
largest coin still does not guarantee the smallest number of coins.
a) Counterexample :
i) Consider coin denominations: {1, 2, 4, 8}. Target amount = 11.
1) Greedy approach: Start with the largest coin (8), subtract it once, then use
one 2 and one 1. The optimal solution for 11 would be one 4 and one 2,
which uses fewer coins than the greedy approach.