#85 Maximal Rectangle

Description

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.

Examples

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 = []
Output: 0

Example 3:

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

Example 4:

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

Example 5:

Input: matrix = [[“0”,“0”]]
Output: 0

Constraints:

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

Solution

这道题我一开始也想着用动态规划做的!!(和动态规划过不去了),但状态转移式子一直都搞不好,会有酱酱酿酿的特殊情况

所以还是简简单单,先计算每一排所有的Max_height,再将它转换为#84比较好(lc也是用心了,把这两题放在一起)

(甚至直接用了上一题的代码没有重新写

代码

class Solution {
    public int largestRectangleArea(int[] heights) {
        int answer = 0;
        int[] position = new int[heights.length];
        int i, j;
        for(i = 0; i < heights.length; i++){
            if(i > 0 && heights[i] == heights[i - 1]){
                position[i] = position[i - 1];
                continue;
            }
            int temp = heights[i];
            for(j = i - 1; j >= 0; j--){
                if (heights[i] > heights[j])
                    break;
                else
                    j = position[j] + 1;
            }
            position[i] = j;
            temp = temp + (i - j - 1) * heights[i];
            for(j = i + 1; j < heights.length; j++){
                if (heights[i] > heights[j])
                    break;
            }
            temp = temp + (j - i - 1) * heights[i];
            if(answer < temp)
                answer = temp;
        }
        return answer;
    }
    
    public int maximalRectangle(char[][] matrix) {
        int row = matrix.length;
        if(row == 0)
            return 0;
        int col = matrix[0].length;
        int[] height = new int[col];
        int answer = 0;
        
        int i, j;
        for(i = 0; i < col; i++){
            height[i] = matrix[0][i] - '0';
        }
        answer = Math.max(answer, largestRectangleArea(height));
        for(i = 1; i < row; i++){
            for(j = 0; j < col; j++){
                if(matrix[i][j] == '0'){
                    height[j] = 0;
                    continue;
                }
                height[j] = height[j] + 1;
            }
            answer = Math.max(answer, largestRectangleArea(height));
        }
        return answer;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值