1. 程式人生 > 實用技巧 >20201226 最大矩形(困難)

20201226 最大矩形(困難)

給定一個僅包含0 和 1 、大小為 rows x cols 的二維二進位制矩陣,找出只包含 1 的最大矩形,並返回其面積。



示例 1:


輸入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
輸出:6
解釋:最大矩形如上圖所示。
示例 2:

輸入:matrix = []
輸出:0
示例 3:

輸入:matrix = [["0"]]
輸出:0
示例 4:

輸入:matrix = [["1"]]
輸出:1
示例 5:

輸入:matrix = [["0","0"]]
輸出:
0 來源:力扣(LeetCode) 連結:https://leetcode-cn.com/problems/maximal-rectangle 著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
    public int maximalRectangle(char[][] matrix) {
        int m = matrix.length;
        if (m == 0) {
            return 0;
        }
        int n = matrix[0].length;
        int
[][] left = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1; } } } int ret = 0; for (int
j = 0; j < n; j++) { // 對於每一列,使用基於柱狀圖的方法 int[] up = new int[m]; int[] down = new int[m]; Deque<Integer> stack = new LinkedList<Integer>(); for (int i = 0; i < m; i++) { while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) { stack.pop(); } up[i] = stack.isEmpty() ? -1 : stack.peek(); stack.push(i); } stack.clear(); for (int i = m - 1; i >= 0; i--) { while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) { stack.pop(); } down[i] = stack.isEmpty() ? m : stack.peek(); stack.push(i); } for (int i = 0; i < m; i++) { int height = down[i] - up[i] - 1; int area = height * left[i][j]; ret = Math.max(ret, area); } } return ret; } }