You are on page 1of 2

You are given n integers in the range [1, m] and a target T.

Find a subset of the n integers whose sum is as


close to T as possible without exceeding it. Consider following greedy approach for solving this problem.

Sort number in descending order. Start adding numbers in subset starting from largest number. Terminate
at the number for which the sum exceeds T.

Prove this greedy strategy is not optimal by giving counter example.

Greed fails on the following case:

T= 21

5 integers picked from [1…10]: {10, 10, 8, 8, 5};

Algo will pick: 10, 10


Optimal: 8, 8, 5

Does topological sort exist for following graph? If yes, show topological sort order of vertices otherwise
state the reason why it not possible.

Topological sort does not exist because the graph is not a DAG so there is no unique (partial)
order of the nodes.

Under a Huffman encoding of n symbols with frequencies f1, f2, …, fn, what is the longest a code could
possibly be? Give an example set of frequencies for at least 5 characters that would produce this case.
Department of Computer Science Page1
In the worst case, we will get a full binary tree of height n-1, hence the longest code would be
(n-1) bit long.

This happens specifically when one the latest insert (combined) node happens to be one of the
two lighest nodes in the next iteration, for each iteration.

Example frequenceies: (A, 5), (B, 5), (C, 15), (D, 30) , (E, 60)

This will produce the following tree

-
/ \
E -

/ \
D -
/ \
C -
/ \
A B

Department of Computer Science Page2

You might also like