leetcode do question notes 85 largest rectangle

Given a   2-D binary matrix of   size  containing only 0 and  , find  the largest rectangle containing only and return its area.1rows x cols1

Example 1:

 Idea 1: Monotonic stack

int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize){
    int dp[matrixSize][matrixColSize[0] + 2];
    memset(dp, 0, sizeof(dp));//初始化
    for(int i = 0; i < matrixSize; i++)
    {
        for(int j = 0; j < matrixColSize[0]; j++)
        {
            if(matrix[i][j] == '1')
            {
                dp[i][j+1] = (i == 0 ? 0 : dp[i-1][j+1])+1;
            }
        }
    }
    int max = 0;
    for(int i = 0; i < matrixSize; i++)
    {
        int stack[matrixColSize[0]+2];
        int top = -1;
        stack[++top] = 0;
        for(int j = 1; j < matrixColSize[0]+2; j++)
        {
                while(dp[i][j] < dp[i][stack[top]])
                {
                    max = fmax(max, (j - stack[top-1] - 1) * dp[i][stack[top]]);
                    --top;
                }
                stack[++top] = j;
        }
    }
    return max;
}

 analyze:

This question is similar to the previous question, and it is also a monotone stack solution, which can convert the rectangle into length and width, calculate the maximum value of the product of length and width, calculate the maximum value of the rectangle according to the monotonically decreasing recursion to the minimum value, and finally return the answer

Summarize:

This question examines the application of the monotone stack. In addition, this question can also be solved by the method of dynamic programming. The monotone stack solution pays attention to the processing of arrays. The input is a string, which is different from the number processing method.

Guess you like

Origin blog.csdn.net/si_mple_/article/details/132350530