100 likes | 206 Views
Greedy Algorithm CSCI3160 tutorial (7 t h week) Office: SHB 913 Office Hour: (Mon) 10:00 -12:00 Email: jjye@cse.cuhk.edu.hk. Ye Junjie. Outline. Greedy Algorithm Find an optimal s olution Coin Changing Buy and Sell Stock Cannot find an optimal solution Bin Packing.
E N D
Greedy Algorithm CSCI3160 tutorial (7th week)Office: SHB 913 Office Hour: (Mon) 10:00 -12:00 Email: jjye@cse.cuhk.edu.hk Ye Junjie
Outline Greedy Algorithm Find an optimal solution Coin Changing Buy and Sell Stock Cannot find an optimal solution Bin Packing
Coin Changing Suppose that in a certain country, the coin dominations consist of: $1, $2, $5, $10 Design an algorithm such that you can make change of any x dollars using the fewest number of coins.
Coin Changing Coin Changing: 1. Create an empty bag 2. while (x > 0) { Find the largest coin c at most x; Put c in the bag; Set x = x –c ; } 3. Return coins in the bag
Buy and Sell Stock Say you have an array A[1…n]for which the i-thelement is the price of a given stock on day i. You are permitted to complete at most one transaction (buy one and sell one share of the stock). Design an algorithm to find the maximum profit.
Buy and Sell Stock Use m and p to denote the minimum price and best profit so far. 1. Set p = 0, m = A[1]. 2. for i from 1 to n { If A[i] < m, m = A[i]. else if A[i] – m > p, p = A[i] – m. }
Bin Packing Bin Packing: In the bin packing problem, objects of different volumes must be packed into a finite number of bins or containers each of volume V in a way that minimizes the number of bins used. There are many variations of this problem, such as 2D packing, linear packing, packing by weight, packing by cost, and so on. http://en.wikipedia.org/wiki/Bin_packing_problem
Bin Packing First-fit Algorithm: The algorithm processes the items in arbitrary order. For each item, it attempts to place the item in the first bin that can accommodate the item. If no bin is found, it opens a new bin and puts the item within the new bin. How good is the greedy algorithm comparing the optimal solution?
Bin Packing First-fit Algorithm: It is impossible for 2 bins to be at most half full. Otherwise, it means at some point one bin is at most half full and we open a new bin to accommodate an item of size at most half capacity. Thus if we have B bins, at least B − 1 bins are more than half full. We have B ≤ 2OPT. Other Algorithms: Best-fit and etc…
Thank you! Q&A