原题链接在这里:
题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 6.
题解:
用数组heights存储一行中值为1的点的最大高度,然后像算这一行能产生的最大面积maxRec.
Time Complexity: O(m*n). m = matrix.length. n = matrix[0].length.
Space: O(n).
AC Java:
1 class Solution { 2 public int maximalRectangle(char[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 4 return 0; 5 } 6 7 int res = 0; 8 int m = matrix.length; 9 int n = matrix[0].length;10 int [] heights = new int[n];11 for(int i = 0; istk = new Stack ();30 stk.push(-1);31 for(int i = 0; i =heights[i]){33 int h = heights[stk.pop()];34 res = Math.max(res, h*(i-stk.peek()-1));35 }36 37 stk.push(i);38 }39 40 while(stk.peek() != -1){41 res = Math.max(res, heights[stk.pop()]*(heights.length-stk.peek()-1));42 }43 44 return res;45 }46 }
类似.