You are on page 1of 2

// Online Java Compiler

// Use this editor to write, compile and run your Java code online
import java.util.*;
class Solution {
public static void maxArea(int mat[][], int r, int c){
int arr[] = new int[c];
int m =0, res =0;
for(int i=0; i<r; i++){
for(int j=0;j<c;j++){
if (i==0){
arr[m] = mat[i][j];
} else {
if (mat[i][j] == 1){
arr[m] += mat[i][j];
} else {
arr[m] = 0;
}
}
m++;
}
m=0;
res = Math.max(res,maxHist(arr,c));
}
System.out.println("max area ="+res);
}
public static int maxHist(int arr[], int c){
Stack<Integer> stk = new Stack<Integer>();
int area[] = new int[c];
int mx = Integer.MIN_VALUE;
stk.push(0);
area[0] = arr[0];
for(int i=1;i<c;i++){
// System.out.println(" i+ "+i);
while (!stk.isEmpty()){
if (arr[i]<=arr[stk.peek()]){
stk.pop();
} else {
break;
}
}
if(!stk.isEmpty()){
area[i] = arr[i] * (i - stk.peek());
} else {
area[i] = arr[i] * (i+1);
}
stk.push(i);
}

for(int i=0;i<area.length;i++){
if (mx<area[i]){
mx = area[i];
}
}
System.out.println(" mx "+mx);
return mx;
}
public static void main(String[] args) {
int mat[][] = {{0,1,1,0},
{1,1,1,1},
{1,1,1,1},
{1,1,0,0}};
int R=4,C=4;
maxArea(mat,R,C);
}
}

You might also like