-
Notifications
You must be signed in to change notification settings - Fork 2
/
84.largest-rectangle-in-histogram.java
81 lines (73 loc) · 1.96 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
/*
* @lc app=leetcode id=84 lang=java
*
* [84] Largest Rectangle in Histogram
*
* https://leetcode.com/problems/largest-rectangle-in-histogram/description/
*
* algorithms
* Hard (35.34%)
* Likes: 4431
* Dislikes: 93
* Total Accepted: 295.4K
* Total Submissions: 824K
* Testcase Example: '[2,1,5,6,2,3]'
*
* Given n non-negative integers representing the histogram's bar height where
* the width of each bar is 1, find the area of largest rectangle in the
* histogram.
*
*
*
*
* Above is a histogram where width of each bar is 1, given height =
* [2,1,5,6,2,3].
*
*
*
*
* The largest rectangle is shown in the shaded area, which has area = 10
* unit.
*
*
*
* Example:
*
*
* Input: [2,1,5,6,2,3]
* Output: 10
*
*
*/
// @lc code=start
class Solution {
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
int[] lessFromLeft = new int[heights.length]; // idx of the first bar the left that is lower than current
int[] lessFromRight = new int[heights.length]; // idx of the first bar the right that is lower than current
lessFromRight[heights.length - 1] = heights.length;
lessFromLeft[0] = -1;
for (int i = 1; i < heights.length; i++) {
int p = i - 1;
while (p >= 0 && heights[p] >= heights[i]) {
p = lessFromLeft[p];
}
lessFromLeft[i] = p;
}
for (int i = heights.length - 2; i >= 0; i--) {
int p = i + 1;
while (p < heights.length && heights[p] >= heights[i]) {
p = lessFromRight[p];
}
lessFromRight[i] = p;
}
int maxArea = 0;
for (int i = 0; i < heights.length; i++) {
maxArea = Math.max(maxArea, heights[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
}
return maxArea;
}
}
// @lc code=end