MCPcopy Index your code
hub / github.com/Tiwarishashwat/InterviewCodes / findMax

Method findMax

MaximumRectangleInMatrix.java:4–40  ·  view source on GitHub ↗
(int arr[], int n)

Source from the content-addressed store, hash-verified

2class Solution {
3
4 public static int findMax(int arr[], int n)
5 {
6 int res=0,h=0,p=0,i=1;
7 Stack<Integer> startPos = new Stack<>();
8 Stack<Integer> height = new Stack<>();
9 startPos.push(0);
10 for(i=0;i<n;i++)
11 {
12 // Empty or when a bigger value arrives we start a new rectangle
13 if(height.isEmpty() || arr[i]>height.peek())
14 {
15 startPos.push(i);
16 height.push(arr[i]);
17 }
18 // Pop logic
19 else if( arr[i]<height.peek())
20 {
21 while(!height.isEmpty() && arr[i]<height.peek())
22 {
23 h=height.pop();
24 p=startPos.pop();
25 res=Math.max(res,h*(i-p));
26 }
27 // Store the last popped value to retrive the current value's starting
28 startPos.push(p);
29 height.push(arr[i]);
30 }
31 }
32 // Remaining values
33 while(!height.isEmpty())
34 {
35 h=height.pop();
36 p=startPos.pop();
37 res=Math.max(res,h*(i-p));
38 }
39 return res;
40 }
41
42 public int maxArea(int M[][], int m, int n) {
43 // add code here.

Callers 1

maxAreaMethod · 0.95

Calls 3

pushMethod · 0.80
popMethod · 0.80
isEmptyMethod · 0.45

Tested by

no test coverage detected