Sunday, June 12, 2016

Maximal Rectangle -- LeetCode

[Question]
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

[Analysis]
Scanning the matrix line by line, the 1's in scanned portion composed a histogram. Calculating the largest rectangle area in each histogram will give the final answer of the maximum area overall. The time complexity is O(MxN), if the matrix is M rows and N columns.

[References]
1. Largest rectangle area in histogram.
2. Minimum Value in Queue.
3. Container with the most water.

[Solution]
class Solution {
public:
    int maxRect(vector<int> &vec) {
        if (vec.size()==0) return 0;
     
        stack<int> st;
        int max_area = 0;
     
        for(int i=0; i<vec.size()+1; i++) {
            int next = (i<vec.size())? vec[i]:0;
         
            while(!st.empty() && next<vec[st.top()]) {
                int ind = st.top();
                st.pop();
                int area = (st.empty())? i*vec[ind]:(i-st.top()-1)*vec[ind];
                max_area = max(area, max_area);
            }
            st.push(i);
        }
        return max_area;
    }
 
    int maximalRectangle(vector<vector<char> > &matrix) {
        if (matrix.size()==0) return 0;
     
        vector<int> histogram (matrix[0].size(), 0);
        int max_area = 0;
     
        for(int i=0; i<matrix.size(); i++) {
            //... for each line, generate histogram and count the maximal rect on the histogram
            //...
            for (int j=0; j<matrix[0].size(); j++) {
                histogram[j] = (matrix[i][j]=='0')? 0: histogram[j]+1;
            }
            int area = maxRect(histogram);
            max_area = max(area, max_area);
        }
        return max_area;
    }
};

No comments:

Post a Comment