Skip to content

Instantly share code, notes, and snippets.

View ajinkyajawale14499's full-sized avatar
🎯
Focusing

Ajinkya ajinkyajawale14499

🎯
Focusing
View GitHub Profile
@ajinkyajawale14499
ajinkyajawale14499 / Largest_Histogram_DP.java
Created June 29, 2019 18:47
Largest Histogram using dynamic programming
public static int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current
int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current
lessFromRight[height.length - 1] = height.length;
lessFromLeft[0] = -1;
for (int i = 1; i < height.length; i++) {
@ajinkyajawale14499
ajinkyajawale14499 / Largest_Histogram_stack2.java
Created June 29, 2019 18:27
Largest Histogram stack improvised solution
public class Solution {
public int largestRectangleArea(int[] height) {
int len = height.length;
Stack<Integer> s = new Stack<Integer>();
int maxArea = 0;
for(int i = 0; i <= len; i++){
int h = (i == len ? 0 : height[i]);
if(s.isEmpty() || h >= height[s.peek()]){
s.push(i);
}else{
@ajinkyajawale14499
ajinkyajawale14499 / largest_histogram_stack.py
Created June 29, 2019 18:07
largest histogram solution using stack
def largestRectangleArea(self, height):
height.append(0)
stack = [-1]
ans = 0
for i in xrange(len(height)):
while height[i] < height[stack[-1]]:
h = height[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
@ajinkyajawale14499
ajinkyajawale14499 / histogram_dummy_zero.java
Created June 29, 2019 17:49
histogram dummy zero trick using stack
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
height.insert(height.begin(),0); // dummy "0" added to make sure stack s will never be empty
height.push_back(0); // dummy "0" added to clear the stack at the end
int len = height.size();
int i, res = 0, idx;
stack<int> s; // stack to save "height" index
s.push(0); // index to the first dummy "0"
for(i=1;i<len;i++)