lab6
lab6
Lab 6
Exercise 1: Consider the recursive makeChange implementation in the lecture notes, without
memoization:
What’s the running time of this function in terms of n when L is the list [1,2]?
Hint: You’ve already figured out the answer to this in a previous lab.
Exercise 2: Modify the memoized makeChange implementation so that it doesn’t just tell you
the minimum number of coins that are needed to make change, but instead it returns a list of which
coins you should use to make change using the fewest number of coins.
Exercise 3: Write a function lis(L) which takes as input a list of integers L and outputs the
length of the longest increasing subsequence (lis) of L. A subsequence of L is a sublist of L that does
not have to be contiguous. For example, [1, 5, 9] is a subsequence of the list L = [1,2,3,4,5,6,7,8,9]
since 1,5,9 appear in the list L in the same order (though just not in a row). 9,5,1 is not a
subsequence of L since it does not appear in L in that order.
Your implementation should run in time O(m2 ) where the size of L is m. Bonus (try at the
end): See if you can find a way to solve the problem in O(m log m) time.
1
Exercise 5: In the knapsack problem we assume we have a bag that can hold some n liters of
volume, and we want to pack the bag with the most valuable combination of items possible out
of some given list of items. Implement a function knapsack(n, L) which takes as input this bag
volume n, and a list of items L, and returns the maximum value you can pack in the bag. L is a list
of lists, where each list in L is of size 2 containing the volume of the item as its 0th element, and
its volume as its 1st element. For example, L = [[7, 10], [5, 6], [4, 5]] represents a list of 3 items.
The first item takes 7 liters and is worth 10 dollars, the second item takes 5 liters and is worth 6
dollars, and the last item takes 4 liters and is worth 5 dollars. knapsack(10, [[7, 10], [5, 6], [4, 5]])
should return 11 since the best thing to do is to take the and and third item (which both fit, since
their total volume is 5 + 4 = 9 liters, and we can fit 10 liters).
Your implementation should run in time O(nm) where the size of L is m.