Skip to content

Commit 3fe8e83

Browse files
authored
Update Maximum Size Rectangle with Binary.java
1 parent 809eb01 commit 3fe8e83

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Stack_Interview Problem/Maximum Size Rectangle with Binary.java

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,107 @@ public static int[] nsr(int arr[],int n){
9292
return right;
9393
}
9494
}
95+
96+
//Leet Code SOln:
97+
class Solution {
98+
public int maximalRectangle(char[][] matrix) {
99+
int n=matrix.length;
100+
int m=matrix[0].length;
101+
int[][] mat = new int[n][m];
102+
for(int i=0;i<n;i++){
103+
for(int j=0;j<m;j++){
104+
if(matrix[i][j]=='0'){
105+
mat[i][j]=0;
106+
}else{
107+
mat[i][j]=1;
108+
}
109+
}
110+
}
111+
return maximalAreaOfSubMatrixOfAll1(mat,n,m);
112+
113+
}
114+
public static int maximalAreaOfSubMatrixOfAll1(int[][] mat, int n, int m) {
115+
//Lets Play with Stack :: MAH Problem :: break into 1-D array::
116+
int area=0;
117+
int temp[] = new int[m];
118+
for(int j=0;j<m;j++){
119+
temp[j] =mat[0][j];
120+
}
121+
122+
area = MAH(temp, m);
123+
for(int i=1;i<n;i++){
124+
int maxi=0;
125+
for(int j=0;j<m;j++){
126+
if(mat[i][j]==0){
127+
temp[j]=0;
128+
}else{
129+
temp[j] =temp[j]+mat[i][j];
130+
}
131+
}
132+
//System.out.println();
133+
maxi =MAH(temp, m);
134+
//System.out.print(maxi+" ");
135+
area =Math.max(maxi,area);
136+
}
137+
return area;
138+
139+
}
140+
public static int MAH(int arr[] ,int n){
141+
int[] left =nsl(arr, n);
142+
int[] right =nsr(arr, n);
143+
int width=0;
144+
int area=0;
145+
for(int i=0;i<n;i++){
146+
width =right[i]-left[i]-1;
147+
area=Math.max(width*arr[i],area);
148+
}
149+
return area;
150+
151+
}
152+
public static int[] nsl(int arr[],int n){
153+
int[] left =new int[n];
154+
Stack<Integer> st = new Stack<>();
155+
156+
for(int i=0;i<n;i++){
157+
if(st.isEmpty()){
158+
left[i] =-1;
159+
}else if(arr[st.peek()]<arr[i]){
160+
left[i] =st.peek();
161+
}else{
162+
while(!st.isEmpty() && arr[st.peek()]>=arr[i]){
163+
st.pop();
164+
}
165+
if(st.isEmpty()){
166+
left[i] =-1;
167+
}else{
168+
left[i] =st.peek();
169+
}
170+
}
171+
st.push(i);
172+
}
173+
return left;
174+
}
175+
public static int[] nsr(int arr[],int n){
176+
int[] right =new int[n];
177+
Stack<Integer> st = new Stack<>();
178+
179+
for(int i=n-1;i>=0;i--){
180+
if(st.isEmpty()){
181+
right[i] =n;
182+
}else if(arr[st.peek()]<arr[i]){
183+
right[i] =st.peek();
184+
}else{
185+
while(!st.isEmpty() && arr[st.peek()]>=arr[i]){
186+
st.pop();
187+
}
188+
if(st.isEmpty()){
189+
right[i] =n;
190+
}else{
191+
right[i] =st.peek();
192+
}
193+
}
194+
st.push(i);
195+
}
196+
return right;
197+
}
198+
}

0 commit comments

Comments
 (0)