-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathLargestRectangleinHistogram.java
52 lines (51 loc) · 1.82 KB
/
LargestRectangleinHistogram.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
/*
Author: Andy, [email protected]
Date: Jan 6, 2015
Problem: Largest Rectangle in Histogram
Difficulty: Hard
Source: https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
Notes:
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.
For example,
Given height = [2,1,5,6,2,3],
return 10.
Solution: 1. Only calucate area when reaching local maximum value.
2. Keep a non-descending stack. O(n). if the vector height is not allowed to be changed.
*/
public class Solution {
public int largestRectangleArea_1(int[] height) {
int res = 0;
for (int i = 0; i < height.length; ++i) {
if ((i < height.length - 1) && (height[i] <= height[i+1])) {
continue;
}
int minheight = height[i];
for (int j = i; j >= 0; --j) {
minheight = Math.min(minheight, height[j]);
res = Math.max(res, (i-j+1)*minheight);
}
}
return res;
}
public int largestRectangleArea(int[] height) {
int res = 0;
Stack<Integer> stk = new Stack<Integer>();
int i = 0;
while (i < height.length) {
if (stk.isEmpty() == true || (height[i] >= height[stk.peek()])) {
stk.push(i++);
} else {
int idx = stk.pop();
int width = stk.isEmpty() ? i : (i - stk.peek() - 1);
res = Math.max(res, width*height[idx]);
}
}
while (stk.isEmpty() == false) {
int idx = stk.pop();
int width = stk.isEmpty() ? height.length : (height.length - stk.peek() - 1);
res = Math.max(res, width*height[idx]);
}
return res;
}
}