Problem
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Example
Input :
[
[0,1,1,0],
[0,1,1,0],
[0,1,1,0],
[0,0,0,0]
]
Output : 6
JavaScript Code
function maximalRectangle(matrix) { var m = matrix.length; var n = m == 0 ? 0 : matrix[0].length; var height = []; for (var i = 0; i < m; i++) { var temp = []; for (var j = 0; j < n+1; j++) { temp.push(0); } height.push(temp); } var maxArea = 0; for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { if (matrix[i][j] == '0') { height[i][j] = 0; } else { height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1; } } } for (var i = 0; i < m; i++) { var area = maxAreaInHist(height[i]); if (area > maxArea) { maxArea = area; } } return maxArea; } function maxAreaInHist(height) { var stack = []; var i = 0; var max = 0; while (i < height.length) { if (stack.length == 0 || height[stack[stack.length - 1]] <= height[i]) { stack.push(i++); } else { var t = stack.pop(); max = Math.max(max, height[t] * (stack.length == 0 ? i : i - stack[stack.length - 1] - 1)); } } return max; }
http://lumenstudet.cempaka.edu.my/2014/10/last-note-from-editor-in-chief-of-2014.html?showComment=1642571269070#c8740511630807874172
ReplyDeleteStay on top of the market with our Live, Real-Time Stock Market overview. Get real time Fxit Stock quotes and interactive charts.
ReplyDelete