Dynamic Programming on Squares

Β·

2 min read

DP problems related to squares involve finding the largest or maximal square or rectangle in a matrix or array. To solve these problems effectively, break them into subproblems, define state information , establish recurrence relations, initialize DP tables, and extract final answers

Largest Rectangle in a Histogram

This solution uses the concept of finding the Next Smaller Element (NSE) on the right (nsr) and left (nsl) for each element in the input array. It employs a stack to keep track of the indices of elements that are smaller or equal to the current element. By using this information, it calculates the width of the largest rectangle that can be formed with each element as the height. Finally, it computes the maximum area among all possible rectangles and returns that as the result

Largest Rectangular area will all 1's

  • this problem can be reduced to the largest rectangle in a histogram, we can then calculate max area level by level

vector<int> nextSmallerToLeft(vector<int>& ans){
    // left to right and pop when stack top is GREATER or EQAL
    int n=ans.size();
    vector<int> nsl(n);
    stack<int> st;
    for(int i=0;i<n;i++){
        while (!st.empty() && ans[st.top()] >= ans[i])
            st.pop();
        nsl[i] = st.empty() ? -1: st.top();
        st.push(i);
    }
    return nsl;
}
vector<int> nextSmallerToRight(vector<int>& ans){
    // right to left and pop when stack top is GREATER or EQAL
    int n=ans.size();
    vector<int> nsr(n);
    stack<int> st;
    for(int i=n-1;i>=0;i--){
        while (!st.empty() && ans[st.top()] >= ans[i])
            st.pop();
        nsr[i] = st.empty() ? n: st.top();
        st.push(i);
    }
    return nsr;
}
int largestRectangularAreaInHistogram(vector<int>& histogram){
    vector<int> nsl=nextSmallerToLeft(histogram);
    vector<int> nsr=nextSmallerToRight(histogram);

    int largestArea=INT_MIN;
    for(int i=0;i<histogram.size();i++){
        int l=histogram[i];
        int b=nsr[i]-nsl[i]-1;
        largestArea=max(largestArea,l*b);
    }
    return largestArea;
}
class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n=matrix.size();
        int m=matrix[0].size();
        vector<int> histogram(m,0);
        int ans=INT_MIN;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++)
                histogram[j] = matrix[i][j]=='0' ? 0 : histogram[j]+1;
            ans=max(ans,largestRectangularAreaInHistogram(histogram));
        }
        return ans;
    }
};

Count Square Submatrices will All Ones

Let dp[i][j] represent the number of square matrices will all 1's having BOTTOM-RIGHT as (i,j)

Maximal Square

we can see this is the same problem as `Counting square submatrices` but here a different thing needs to be calculated - the area

Β