Skip to content

Commit

Permalink
Largest Rectangle in Histogram
Browse files Browse the repository at this point in the history
  • Loading branch information
Manish19629 authored Oct 3, 2022
1 parent f019818 commit b60d34c
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions LargestRectangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import java.util.Stack;

public class LargestRectangle {
public static void main(String[] args) {
int[] arr = {2,1,5,6,2,3};

int res = largestRectangleArea(arr);
System.out.println(res);


}
public static int largestRectangleArea(int[] heights) {
int len = heights.length;
Stack<Integer> s = new Stack<>();
int maxArea = 0;
for (int i = 0; i <= len; i++){
int h = (i == len ? 0 : heights[i]);
if (s.isEmpty() || h >= heights[s.peek()]) {
s.push(i);
} else {
int top = s.pop();
maxArea = Math.max(maxArea, heights[top] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}



0 comments on commit b60d34c

Please sign in to comment.