Greedy Is An Algorithmic Paradigm That Builds Up A Solution Piece by Piece, Always
Greedy Is An Algorithmic Paradigm That Builds Up A Solution Piece by Piece, Always
For example, consider the Fractional Knapsack Problem. The problem states that:
Given a list of elements with specific values and weights associated with
them, the task is to fill a Knapsack of weight W using these elements such that
the value of knapsack is maximum possible.
The local optimal strategy is to choose the item that has maximum value vs weight
ratio. This strategy also leads to global optimal solution because we are allowed to
take fractions of an item.
In general, the Greedy Algorithm can be applied to solve a problem if it satisfies the
below property:
At every step, we can make a choice that looks best at the moment, and we
get the optimal solution of the complete problem.
Let us consider one more problem known as the Activity Selection Problem to
understand the use of Greedy Algorithms.
Problem: You are given N activities with their start and finish times. Select the
maximum number of activities that can be performed by a single person, assuming
that a person can only work on a single activity at a time.
The greedy choice is to always pick the next activity whose finish time is least among
the remaining activities and the start time is more than or equal to the finish time of
previously selected activity. We can sort the activities according to their finishing time
so that we always consider the next activity as minimum finishing time activity.
To do this:
o If the start time of this activity is greater than or equal to the finish time
of previously selected activity then select this activity and print it.
Examples:
Input: Four Jobs with following deadlines and profits
JobID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output: Following is maximum profit sequence of jobs
c, a
Implementation:
C++
// Driver Code
int main()
{
Job arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27},
{'d', 1, 25}, {'e', 3, 15}};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Following is maximum profit sequence of job : ";
printJobScheduling(arr, n);
return 0;
}
Run
Java
class GFG
{
// Returns minimum number of platforms reqquired
static void printJobScheduling(Job arr[], int n)
{
// Sort all jobs according to
// decreasing order of prfit
Arrays.sort(arr);
// Driver Code
public static void main(String args[])
{
Job arr[] = {new Job('a', 2, 100),
new Job('b', 1, 19),
new Job('c', 2, 27),
new Job('d', 1, 25),
new Job('e', 3, 15)};
int n = arr.length;
System.out.print("Following is maximum profit"
+" sequence of job : ");
printJobScheduling(arr, n);
}
}
Run
Output:
Following is maximum profit sequence of job : c a e
Time Complexity of the above solution is O(n2). It can be optimized using Disjoint
Set Data Structure. Please refer below post for details.