Greedy Algorithm
Greedy Algorithm
- Make choice that looks best at the moment
- Never reconsider earlier choices
- Hope that the choice will lead to global optimal solution
Activity Selection Problem
- input: n activities with start and finish times
- output: 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
Greedy Choice
- Choose the activity that ends first
Running time: O(nlogn) (Sort first)
When Greedy Works
- When optimal substructure property holds
- Greedy activity selection algorithm exploits a naturaal sub-problem structure: A[i] = number of activities you can do after activity i
Scheduling
-
n tasks, task i takes time, for every hour that passes until task i is completed, you lose dollars
-
Goal: schedule tasks to minimize total loss
Greedy Choice
-
Consider two tasks a and b, a takes x hours, costs z dollars, b takes y hours, costs w dollars
-
cost(A then B) = xz + (x+y)w = x(z+w) + yw
-
cost(B then A) = yw + (x+y)z = xz + y(z+w)
-
Greedy choice: schedule tasks with the biggest .
Huffman Codes
-
Variable-length encoding
-
Prefix-free code: no codeword is a prefix of another codeword
-
Goal: minimize total encoding length
Greedy Choice
-
Merge two least frequent symbols
-
Running time: O(nlogn)
Leetcode examples
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
sort(boxTypes.begin(),boxTypes.end(),[](vector<int>a,vector<int>b){
return a[1]>b[1];
});
int ret=0;
for(int i=0;i<boxTypes.size();++i){
if(boxTypes[i][0]<truckSize){
ret += boxTypes[i][0]*boxTypes[i][1];
truckSize -= boxTypes[i][0];
}else{
ret += truckSize*boxTypes[i][1];
break;
}
}
return ret;
}
};
class Solution {
public:
int maxEvents(vector<vector<int>>& events) {
sort(events.begin(), events.end());
priority_queue<int, vector<int>, greater<int>> pq;
int i = 0, res = 0, n = events.size();
for (int d = 1; d <= 100000; ++d) {
while (i < n && events[i][0] == d) {
pq.push(events[i++][1]);
}
while (!pq.empty() && pq.top() < d) {
pq.pop();
}
if (!pq.empty()) {
pq.pop();
++res;
}
}
return res;
}
};
Comments
Post a Comment