-
Notifications
You must be signed in to change notification settings - Fork 0
/
LargestRectangleFinder.java
42 lines (34 loc) · 1022 Bytes
/
LargestRectangleFinder.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
package org.sean.array;
import java.util.*;
/***
* 84. Largest Rectangle in Histogram
*
* https://leetcode.com/problems/largest-rectangle-in-histogram/
*/
public class LargestRectangleFinder {
public int largestRectangleArea(int[] heights) {
int i = 0;
int len = heights.length;
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
while (i <= len) { // [0, len]
int h = i == len ? 0 : heights[i];
if (stack.isEmpty() || heights[stack.peek()] <= h) {
stack.push(i);
} else { // h < s[top]
int top = stack.pop();
int width;
int elem = heights[top];
if (stack.isEmpty()) {
width = i;
} else {
width = i - stack.peek() - 1;
}
maxArea = Math.max(maxArea, elem * width);
i--;
}
i++;
}
return maxArea;
}
}