-
Notifications
You must be signed in to change notification settings - Fork 2
/
LargestRectangleInHistogram.java
38 lines (34 loc) · 1.12 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
package recursion;
/**
* 84. Largest Rectangle in Histogram
* 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
*
* IMP-1: Common question. Below is a simple two pointer approach.
* See LargestRectangleDivideAndConquer for a faster implementation
*/
public class LargestRectangleInHistogram {
int[] heights;
int maxArea = 0;
public int largestRectangleArea(int[] heights) {
this.heights = heights;
for (int i =0; i < heights.length; i++) {
int minHeight = Integer.MAX_VALUE;
for (int j =i ; j < heights.length; j++) {
minHeight = Math.min(heights[j], minHeight);
int currArea = minHeight * (j-i+1) ;
this.maxArea = Math.max(maxArea, currArea);
}
}
return maxArea;
}
}