LeetCode85. Maximal Rectangle——单调栈

文章目录

一、题目

Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Example 1:

Input: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:

Input: matrix = [[“0”]]
Output: 0
Example 3:

Input: matrix = [[“1”]]
Output: 1

Constraints:

rows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j] is ‘0’ or ‘1’.

二、题解

class Solution {
   
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
   
        int res = 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n,0);
        for(int i = 0;i < m;i++){
   
            for(int j = 0;j < n;j++){
   
                heights[j] = matrix[i][j] == '0' ? 0 : heights[j] + 1;
            }
            res = max(res,largestRectangleArea(heights));
        }
        return res;
    }
    int largestRectangleArea(vector<int>& heights) {
   
        int n = heights.size();
        int res = 0;
        stack<int> st;
        for(int i = 0;i < n;i++){
   
            while(!st.empty() && heights[i] <= heights[st.top()]){
   
                int cur = st.top();
                st.pop();
                int left = st.empty() ? -1 : st.top();
                res = max(res,(i - left - 1) * heights[cur]);
            }
            st.push(i);
        }
        while(!st.empty()){
   
            int cur = st.top();
            st.pop();
            int left = st.empty() ? -1 : st.top();
            res = max(res,(n - left - 1) * heights[cur]);
        }
        return res;
    }
};

相关推荐

  1. LeetCode85. Maximal Rectangle——单调

    2024-01-27 19:48:03       26 阅读
  2. LeetCode75| 单调

    2024-01-27 19:48:03       42 阅读
  3. 算法37:最大矩形(力扣8485题)---单调

    2024-01-27 19:48:03       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-27 19:48:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-27 19:48:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-27 19:48:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-27 19:48:03       18 阅读

热门阅读

  1. 力扣:98. 验证二叉搜索树

    2024-01-27 19:48:03       32 阅读
  2. Android Compose 简单的网络请求框架实例。

    2024-01-27 19:48:03       33 阅读
  3. 15.常用的shell脚本

    2024-01-27 19:48:03       36 阅读
  4. 编程笔记 html5&css&js 060 css响应式布局

    2024-01-27 19:48:03       28 阅读
  5. MyBatis学习笔记

    2024-01-27 19:48:03       37 阅读
  6. Vue3生命周期 VS Vue2生命周期(小记)

    2024-01-27 19:48:03       37 阅读
  7. 【leetcode100-063到068】【二分】六题合集

    2024-01-27 19:48:03       31 阅读
  8. 【C语言】(4)数组

    2024-01-27 19:48:03       32 阅读