1. 程式人生 > 遊戲 >《戰地6》首支預告片完整視訊被洩露

《戰地6》首支預告片完整視訊被洩露

給定一個僅包含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

提示:

rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 為 '0' 或 '1'

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

按照每一行單調棧的思路,來解答。leetcode 84. 柱狀圖中最大的矩形

    private Stack<Integer> index = new Stack<>();
    private Stack<Integer> value = new Stack<>();
    public int maximalRectangle(char
[][] matrix) { if (matrix.length == 0) { return 0; } int b = matrix[0].length; if (b == 0) { return 0; } int m = 0; index.add(-1); value.add(0); int[] arr = new int[b]; for (char[] chars : matrix) {
for (int i = 0; i < b; i++) { if (chars[i] == '0') { arr[i] = 0; } else { arr[i] += 1; } } m = Math.max(m, largestRectangleArea(arr)); } return m; } private int largestRectangleArea(int[] heights) { if (heights == null || heights.length == 0) { return 0; } int length = heights.length; int max = 0; for (int i = 0; i < length; i++) { int v = heights[i]; if (value.peek() > v) { Integer st = index.peek(); while (value.peek() > v) { int item = value.pop(); index.pop(); int l = st - index.peek(); max = Math.max(max, l * item); } } value.add(v); index.add(i); } if (!value.isEmpty()) { Integer st = index.peek(); while (value.size() > 1) { int item = value.pop(); index.pop(); int l = st - index.peek(); max = Math.max(max, l * item); } } return max; }