You are on page 1of 3

DEPARTMENT OF

Experiment3.1
Student Name: Vedprakash Tanwar UID: 20BCS9640
Branch: CSE Section/Group: 20BCS_DM_615-B
Semester: 6 Date of Performance: 02/05/2023
Subject Name: CC LAB Subject Code: 20CSP351

Aim: To demonstrate the concept of greedy algorithm.


Problem 1: Remove Duplicate Letters

class Solution {
public String removeDuplicateLetters(String s) {
int[] lastIndex = new int[26];
for (int i = 0; i < s.length(); i++){
lastIndex[s.charAt(i) - 'a'] = i;
}

boolean[] seen = new boolean[26];


Stack<Integer> st = new Stack();

for (int i = 0; i < s.length(); i++) {


int curr = s.charAt(i) - 'a';
if (seen[curr]) continue;
while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){
seen[st.pop()] = false;
}
st.push(curr);
seen[curr] = true;
}

StringBuilder sb = new StringBuilder();


while (!st.isEmpty())
sb.append((char) (st.pop() + 'a'));
return sb.reverse().toString();
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem 2: Assign Cookies

class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int contentChildren = 0;
int i = 0;
int j = 0;
while (i < g.length && j < s.length) {
if (s[j] >= g[i]) {
contentChildren++;
i++;
}
j++;
}
return contentChildren;
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

You might also like