Max Rectangle

Concepts Used:

DP/recursion and Stack.

Difficulty Level:

Hard.

Problem Statement :

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and print its area.

See original problem statement here

Test Case:

Input:
1
5 5
0 0 1 0 1
0 1 1 1 1
1 1 1 1 1
1 1 1 1 1
0 0 1 1 1

Output:
12

Explanation:
The inner matrix from index (1,1) to index (3,4) with area 12(3*4) gives the appropriate solution.

Solving Approach:

The idea is to update each column of a given row with corresponding column of previous row and find largest histogram area for for that row using data structures and algorithms.

Steps:

  1. Find maximum area for row[0]
  2. for each row in 1 to N – 1
    for each column in that row
    if A[row][column] == 1 then update A[row][column] with A[row][column] += A[row - 1][column]
    find area for that row
    and update maximum area so far

    Solutions:

        #include <bits/stdc++.h> 
        using namespace std; 
        bool sortby(const pair<int, int>& a, 
                const pair<int, int>& b) 
        { 
        if (a.first != b.first) 
            return a.first < b.first; 
        return (a.second < b.second); 
        } 
        bool kOverlap(vector<pair<int, int> > pairs, int k) 
        { 
        vector<pair<int, int> > vec; 
        for (int i = 0; i < pairs.size(); i++) { 
    
            vec.push_back(make_pair( pairs[i].first, -1 )); 
            vec.push_back(make_pair( pairs[i].second, +1 )); 
        } 
        sort(vec.begin(), vec.end()); 
        stack<pair<int, int> > st; 
        for (int i = 0; i < vec.size(); i++) { 
            pair<int, int> cur = vec[i]; 
            if (cur.second == -1) { 
                st.push(cur); 
            } 
            else { 
                st.pop(); 
            } 
            if (st.size() >= k) { 
                return true; 
            } 
        } 
        return false; 
        } 
         int main()
        {  
        int t;
        cin>>t;
        while(t--)
        {
        int n,k;
        cin>>n>>k;
        vector<pair<int, int> > pairs; 
        int x,y;
        for(int i=0;i<n;i++)
        {
            cin>>x>>y;
            pairs.push_back(make_pair(x,y));
        }
        if(kOverlap(pairs,k))
        cout<<"Yes"<<endl;
        else
        {
            cout<<"No"<<endl;
        }
        } 
        return 0;
        }
    

Previous post Samir String
Next post K overlapping segment

Leave a Reply

Your email address will not be published. Required fields are marked *