0% found this document useful (0 votes)
10 views5 pages

AP 3.1 Dhruv

Uploaded by

KARTIK SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

AP 3.1 Dhruv

Uploaded by

KARTIK SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

DEPARTMENTOF

COMPUTERSCIENCE&ENGINEERING

Experiment 3.1

Student Name: Kartik Singh UID: 21BCS8995


Branch: BE-CSE B
Section/Group:646-A
Date: 25-03-2024 Subject: Advanced Programming II

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.

Problem 2: Assume you are an awesome parent and want to give


your children some cookies. But you should give each child at most one
cookie. Each child i has a greed factor g[i], which is the minimum size of
a cookie that the child will be content with; and each cookie j has a size
s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i
will be content. Your goal is to maximize the number of your content
children and output the maximum number.
Script and Output:
DEPARTMENTOF
COMPUTERSCIENCE&ENGINEERING

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:

You might also like