-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path84. Largest Rectangle in Histogram.java
115 lines (83 loc) · 3.07 KB
/
84. Largest Rectangle in Histogram.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class Solution {
// https://leetcode.com/problems/largest-rectangle-in-histogram/
// :::IMPORTANT QUESTION:::
public int largestRectangleArea(int[] heights) {
// TC: O(N)
// SC: O(N)
int n = heights.length;
int gmaxAns = 0;
// stack
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
// remove all the biggest elements from the stack than the current height[i]
while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
int element = heights[stack.pop()];
int nse = i;
int pse = stack.isEmpty() ? -1 : stack.peek();
int width = nse - pse - 1;
int height = element;
int area = width * height;
gmaxAns = Math.max(gmaxAns, area);
}
stack.add(i); // add index not the value
}
// to process the left over elems
while (!stack.isEmpty()) {
int nse = n;
int element = stack.isEmpty() ? -1 : heights[stack.pop()];
int pse = stack.isEmpty() ? -1 : stack.peek();
gmaxAns = Math.max(gmaxAns, element * (nse - pse - 1));
}
return gmaxAns;
}
public int largestRectangleArea2(int[] heights) {
// TC: O(N + N)
// SC: O(2N)
int[] leftWalls = getLeftHeightIndcies(heights);
int[] rightWalls = getRightHeightIndices(heights);
int maxarea = 0;
for (int i = 0; i < heights.length; i++) {
int leftwall = leftWalls[i]; // left wall index
int rightWall = rightWalls[i]; // right wall index
int width = (rightWall - leftwall - 1);
int height = heights[i];
int area = width * height;
maxarea = Math.max(maxarea, area);
}
return maxarea;
}
private int[] getRightHeightIndices(int[] heights) {
// TODO Auto-generated method stub
final int n = heights.length;
int[] walls = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
int curHeight = heights[i];
while (stack.isEmpty() == false && heights[stack.peek()] >= curHeight)
stack.pop();
if (stack.isEmpty() == true)
walls[i] = n;
else
walls[i] = stack.peek();
stack.push(i);
}
return walls;
}
private int[] getLeftHeightIndcies(int[] heights) {
// TODO Auto-generated method stub
final int n = heights.length;
int[] walls = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
int curheight = heights[i];
while (stack.isEmpty() == false && heights[stack.peek()] >= curheight)
stack.pop();
if (stack.isEmpty() == true)
walls[i] = -1;
else
walls[i] = stack.peek();
stack.push(i);
}
return walls;
}
}