Greedy Flashcards

1
Q

Greedy Algorithms

A

Useful for optimization problems for example maximizing or minimizing something.
Greedy algorithms may not always work/ give most optimal solution consider coins[]= {18, 1, 10} and amount =20. Here, greedy outputs coins required = while optimal is 2.
Another example is longest path.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Greedy general structure

A
General structure:
getOptimal(Item arr[], int n):
  res=0
  while all items not considered:
        i = selectAnItem()
        if feasible(i):
             res = res +i
   return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Applications of Greedy Approach

A

Finding optimal solutions: Activity selection, fractional knapsack, job sequencing, Prim’s algo, Kruskal’s, Dijktra’s, Huffman coding.

Finding close to optimal solutions for NP Hard Problems like TSP.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Job Sequencing Problem

A

Every job has a deadline that needs to be met in order to earn profit. Target is to maximize the profit.
Rules:
1. Every job takes 1 unit of time.
2. Only one job can be assigned at a time.
3. Time starts with 0.

Optimal greedy algorithm:
Sort jobs in decreasing order of profit and find the maximum deadline. Then initialize the result array with first job in the sorted list. Assign the latest possible slot.
for remaining (N-1) jobs: if this job cannot be added, ignore else add it to the latest possible slot.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Infinite supply of following coins: 10, 5, 2, 1. Pay a given amount using minimum no of coins.

A

Consider the coins in decreasing order of value. Then check how many coins of greater elements can fit in the amount.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Activity Selection Problem

A

Find maximum number of activities that can be performed on a single machine given a no of machine with {start time, end time) tuples. We can only perform a single task at a time. (Can also be solved by DP by converting into LICS problem.

Much better greedy solution: Sort the job tuples by the finish time (ascending). Initialize solution by first activity.
For remaining activities: if current activity overlaps with the last picked activity, ignore the current activity else add it to the solution. Time: O(nlogn)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Fractional Knapsack

A

Given n items with tuples (weight, value) and the max capacity of knapsack, find the max value that can fit.

Sort the items by the ratio (value/weight) in decreasing order. Then for each element in sorted order: if item weight <= curr capacity: add element, reduce capacity or else take fraction value*(cap/wt) and return result.
Time: O(nlogn + n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly