File tree 1 file changed +70
-0
lines changed
1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int largestRectangleArea(int[] h) {
3
+ //Check null condition
4
+ if(h == null || h.length == 0) return 0;
5
+
6
+ //Initialize variables left and right
7
+ int n = h.length;
8
+ int[] left = new int[n];
9
+ left[0] = -1;
10
+
11
+ int[] right = new int[n];
12
+ right[n-1] = n;
13
+
14
+ //Fill left array
15
+ for(int i = 1; i < n; i++) {
16
+ int prev = i-1;
17
+ while(prev >= 0 && h[prev] >= h[i]){
18
+ prev = left[prev];
19
+ }
20
+ left[i] = prev;
21
+ }
22
+
23
+ //Fill right array
24
+ for(int i = n-2; i >= 0; i--){
25
+ int prev = i+1;
26
+ while(prev < n && h[prev] >= h[i]){
27
+ prev = right[prev];
28
+ }
29
+ right[i] = prev;
30
+ }
31
+
32
+ int maxArea = 0;
33
+ for(int i = 0; i < n; i++) {
34
+ maxArea = Math.max(maxArea, h[i] * (right[i]-left[i]-1));
35
+ }
36
+
37
+ return maxArea;
38
+ }
39
+ }
40
+
41
+ class Solution {
42
+ public int largestRectangleArea(int[] h) {
43
+ //Check null condition
44
+ if(h == null || h.length == 0) return 0;
45
+
46
+ //Initialize variables left and right
47
+ int n = h.length;
48
+ Stack<Integer> stack = new Stack<>();
49
+ int maxArea = 0;
50
+
51
+ for(int i = 0; i <= n; i++) {
52
+ int ht = (i == n) ? 0 : h[i];
53
+ //If stack is empty of ht >= h[top] push in stack
54
+ //Else process the elements and find area.
55
+
56
+ if(stack.isEmpty() || ht >= h[stack.peek()]) {
57
+ stack.push(i);
58
+ }
59
+ else {
60
+ //Process elements and find the mexArea for popped index
61
+ int top = stack.pop();
62
+ int width = (stack.isEmpty()) ? i : (i - stack.peek() - 1);
63
+ int area = h[top] * width;
64
+ maxArea = Math.max(maxArea, area);
65
+ i--;
66
+ }
67
+ }
68
+ return maxArea;
69
+ }
70
+ }
You can’t perform that action at this time.
0 commit comments