Skip to content

Commit f9423bd

Browse files
committed
added Maximum area rectangle in histogram problem
1 parent d208018 commit f9423bd

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.*;
2+
import java.io.*;
3+
4+
public class MaximumArea {
5+
6+
public static void main(String[] args){
7+
int hist[] = {2, 1, 4, 5, 1, 3, 3};
8+
int maximumArea = largestRectangleArea(hist);
9+
System.out.println(maximumArea);
10+
}
11+
12+
public static int largestRectangleArea(int[] A) {
13+
Stack<Integer> st = new Stack<Integer>();
14+
int ans = 0;
15+
for (int i = 0 ; i < A.length || !st.isEmpty(); ){
16+
if (i >= A.length){
17+
ans = Math.max(ans, A[st.pop()] * (st.isEmpty() ? i : i - st.peek() - 1) );
18+
continue;
19+
}
20+
if (st.isEmpty() || A[st.peek()] <= A[i]){
21+
st.push(i++);
22+
}else if (A[st.peek()] > A[i]){
23+
ans = Math.max(ans, A[st.pop()] * (st.isEmpty() ? i : i - st.peek() - 1) );
24+
}
25+
}
26+
return ans;
27+
}
28+
}
29+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Largest Rectangle in a Histogram
2+
3+
** 2003/2004 ACM ICPC University of Ulm Local Contest **
4+
5+
A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights.Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Given, heights of rectangles, calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too.
6+
7+
### Example:
8+
**Input** : `[2, 1, 4, 5, 1, 3, 3]`
9+
10+
**Output:** : `8`

0 commit comments

Comments
 (0)