-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRectArea.java
More file actions
44 lines (40 loc) · 1.29 KB
/
RectArea.java
File metadata and controls
44 lines (40 loc) · 1.29 KB
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
class Result {
/*
* Complete the 'largestRectangle' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts INTEGER_ARRAY h as parameter.
*/
public static long largestRectangle(List<Integer> h) {
int i=0;
int maxarea=0;
int currarea=0;
int top=0;
Stack<Integer> stack=new Stack<Integer>();
while(i<h.size()){
if(stack.isEmpty() || h.get(stack.peek())<=h.get(i)){
//System.out.println(i+" "+"if");
stack.push(i++);
}
else{
top=stack.pop();
int width=0;
if(stack.isEmpty())width=i;
else width=i-stack.peek()-1;
//System.out.println(i+" "+"else"+" "+stack.peek());
currarea=h.get(top)*width;
maxarea=Math.max(maxarea,currarea);
}
}
while(!stack.isEmpty()){
top=stack.pop();
int width=0;
if(stack.isEmpty())width=i;
else width=i-stack.peek()-1;
//System.out.println(i+" "+"else"+" "+stack.peek());
currarea=h.get(top)*width;
maxarea=Math.max(maxarea,currarea);
}
return maxarea;
}
}