These are two popular examples of Greedy Algorithms. 1. Fractional Knapsack ProblemGiven the weight of items along with its value and also the maximum weight that we can to take, we have to maximize the value we can get. Unlike 0-1 knapsack, here we are allowed to take fractional items. Hence this problem is called fractional knapsack. Fractional knapsack problem is solvable by greedy strategy. Greedy algorithm – It obtains the solution of a problem by making a sequence of choices. At each decision point, the best possible choice is made. The basic idea is to calculate for each item the ratio of value/weight, and sort them according to this ratio. Then take the items with the highest ratios and add them until we can’t add the next item as whole. Finally add as much as you can of the next item. Properties If the items are already sorted into decreasing order of vi / wi, then the for-loop takes O(n) time. Where n is the total number of items. Therefore, the total time including the sort is in O(n log n) as quicksort’s average time complexity is O(nlogn). Complete Tutorial for the Fractional Knapsack Problem : Fractional Knapsack Problem - C Program Source Code#include<stdio.h> 2. Task Scheduling ProblemTask SchedulingGiven a set of events, our goal is to maximize the number of events that we can attend. Let E ={1,2,3…n} be the events we need to attend. Each event has a start time si and a finish time fi, where si < fi. Events i and j are compatible if the intervals [si , fi) and [sj , fj) do not overlap (i.e., i and j are compatible if si ≥ fj or sj ≤ fi. The goal is to select a maximum-size set of mutually compatible events. Greedy algorithm is used for solving this problem. For this we need to arrange the events in order of increasing finish time: f1 ≤ f2 ≤ ……≤ fn. Properties If the events are already sorted into increasing order of fi , then the for-loop takes O(n) time. Where n is the total number of events. Therefore, the total time including the sort is in O(n log n) as quicksort’s average time complexity is O(nlogn). Complete Tutorial for the Task Scheduling Problem : Task Scheduling - C Program Source Code#include<stdio.h> Related Tutorials ( Common examples of Greedy Algorithms ) :
Some Important Data Structures and Algorithms, at a glance:
| Basic Data Structures and Algorithms Sorting- at a glance
|
Computer Science >