Skip to content

Uploading 2 Leetcode Solutions #527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions LeetCode Solutions/LargestRectangleInHistogram.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class Solution {
private:
vector<int> nextSmallerElement(vector<int> arr, int n) {
stack<int> s;
s.push(-1);
vector<int> ans(n);

for(int i=n-1; i>=0 ; i--) {
int curr = arr[i];
while(s.top() != -1 && arr[s.top()] >= curr)
{
s.pop();
}
//ans is stack ka top
ans[i] = s.top();
s.push(i);
}
return ans;
}

vector<int> prevSmallerElement(vector<int> arr, int n) {
stack<int> s;
s.push(-1);
vector<int> ans(n);

for(int i=0; i<n; i++) {
int curr = arr[i];
while(s.top() != -1 && arr[s.top()] >= curr)
{
s.pop();
}
//ans is stack ka top
ans[i] = s.top();
s.push(i);
}
return ans;
}

public:
int largestRectangleArea(vector<int>& heights) {
int n= heights.size();

vector<int> next(n);
next = nextSmallerElement(heights, n);

vector<int> prev(n);
prev = prevSmallerElement(heights, n);

int area = INT_MIN;
for(int i=0; i<n; i++) {
int l = heights[i];

if(next[i] == -1) {
next[i] = n;
}
int b = next[i] - prev[i] - 1;
int newArea = l*b;
area = max(area, newArea);
}
return area;
}
};
42 changes: 42 additions & 0 deletions LeetCode Solutions/ValidParenthesis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
bool isValid(string expression) {
stack<char> s;
for(int i=0; i<expression.length(); i++) {

char ch = expression[i];

//if opening bracket, stack push
//if close bracket, stacktop check and pop

if(ch == '(' || ch == '{' || ch == '['){
s.push(ch);
}
else
{
//for closing bracket
if(!s.empty()) {
char top = s.top();
if( (ch == ')' && top == '(') ||
( ch == '}' && top == '{') ||
(ch == ']' && top == '[') ) {
s.pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
}

if(s.empty())
return true;
else
return false;
}
};