AP 3.1 Dhruv
AP 3.1 Dhruv
COMPUTERSCIENCE&ENGINEERING
Experiment 3.1
1. Aim:
To demonstrate the concept of Greedy Algorithm.
§ Remove Duplicate Letters §Assign Cookies
2. Objective:
Problem 1: Given a string s, remove duplicate letters so that every
letter appears once and only once. You must make sure your result is the
smallest in lexicographical order among all possible results.
Solution 1:
class Solution {
public:
string removeDuplicateLetters(string s) {
stack<char>st;
map<char,bool>vis;
map<char,int>last;
int n=s.size();
for(int i=0;i<n;i++){
last[s[i]]=i;
}//21BCS8995
for(int i=0;i<n;i++)if(!vis[s[i]]){
while(!st.empty() && st.top()>s[i]){
if(last[st.top()]>i) vis[st.top()]=0,st.pop();
else break;
}
st.push(s[i]);
vis[s[i]]=1;
}
string ans="";
while(!st.empty()){
ans+=st.top();
st.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
DEPARTMENTOF
COMPUTERSCIENCE&ENGINEERING
OUTPUT:
DEPARTMENTOF
COMPUTERSCIENCE&ENGINEERING
Solution 2:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int ans = 0;
//21BCS8995
if (g.size() == 0 || s.size() == 0)
return 0;
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int gi = 0;
int si = 0;
for (auto child : g) {
while (s[si] < child) {
si++;
if (si >= s.size())
return ans;
}
si++;
ans++;
if (si >= s.size())
return ans;
}
return ans;
}
};
DEPARTMENTOF
COMPUTERSCIENCE&ENGINEERING
OUTPUT: