Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit. For example, Given height = [2,1,5,6,2,3], return 10.
Brute Force Solution
for each height, go back and find the largest area. O(n^2)
else{//keep updating when stk.pop is bigger than current
int pre = stk.pop();
int h = height[pre];
int w = stk.isEmpty() ? i : (i-stk.peek()-1);
maxarea = Math.max(maxarea, w * h);
}
}
while(!stk.isEmpty()){//pop the rest
int pre = stk.pop();
int h = height[pre];
int w = stk.isEmpty() ? i : (i-stk.peek()-1);
maxarea = Math.max(maxarea, w * h);
}
return maxarea;
}
Maximal Square
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area. For example, given the following matrix:
1
2
3
4
5
10100
10111
11111
10010
Return4.
DP Solution
max square length with i,j as right-bottom corner
when current cell is 1, dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i-1][j-1]), dp[i][j-1]) + 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
publicintmaximalSquare(char[][] matrix) {
if(matrix==null || matrix.length == 0) return0;
int maxside=0;
int[][] dp = newint[matrix.length][matrix[0].length]; //max square length with i,j as right-bottom corner