LeetCode //C - 85. Maximal Rectangle

85. 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’.

From: LeetCode
Link: 85. Maximal Rectangle


Solution:

Ideas:

1. Histogram Transformation: Each row in the matrix is transformed into a histogram. The height of the bars in this histogram at each column corresponds to the number of consecutive '1’s up to that row. This means if there’s a ‘1’ above the current ‘1’ in the matrix, the bar gets taller by 1. If there’s a ‘0’, the bar’s height resets to zero.

2. Maximal Rectangle in Histogram: For each histogram created from each row of the matrix, the code calculates the area of the largest rectangle that can be formed in that histogram. This calculation is where the stack is used.

  • Using a Stack: The idea is to maintain a stack of indices of the histogram’s bars. Bars are pushed onto the stack if they’re taller than the bar at the stack’s top index. When a shorter bar is encountered, it triggers a calculation:
    • Pop the stack until the current bar is taller than the bar at the top of the stack or the stack is empty.
    • For each popped bar, calculate the rectangle’s area with the popped bar as the shortest bar (height). The width of this rectangle extends from the current bar’s index to the index just beyond the last bar that was less than the popped bar (as indicated by the new top of the stack).
    • Update the maximum area found so far.

3. Iterate Over All Rows: The process is repeated for every row in the matrix, treating each row as the base for a new histogram. This effectively leverages the previous rows’ calculations to build upon them dynamically.

4. Edge Cases: The code handles matrices of any size, including the smallest possible matrix (1x1) and ensures that no memory overflows or illegal accesses occur.

5. Maximal Rectangle Calculation: After processing all rows, the largest area calculated from any histogram is the area of the largest rectangle containing only '1’s in the entire matrix.

Code:
int maximalHistogram(int* heights, int size) {
    if (size == 0) return 0;

    int *stack = (int *) malloc(sizeof(int) * size);
    if (!stack) return 0; // Memory allocation check

    int top = -1;
    int maxArea = 0;
    int area = 0;
    int i = 0;
    while (i <= size) {
        int h = (i == size) ? 0 : heights[i];
        while (top != -1 && h < heights[stack[top]]) {
            int tp = stack[top--];
            int width = (top == -1) ? i : i - stack[top] - 1;
            area = heights[tp] * width;
            if (area > maxArea) {
                maxArea = area;
            }
        }
        if (i < size) {
            stack[++top] = i;
        }
        i++;
    }
    free(stack);
    return maxArea;
}

int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize) {
    if (matrixSize == 0 || matrixColSize[0] == 0) return 0;

    int maxArea = 0;
    int *heights = (int *) calloc(matrixColSize[0], sizeof(int));
    if (!heights) return 0; // Memory allocation check

    for (int i = 0; i < matrixSize; i++) {
        for (int j = 0; j < matrixColSize[i]; j++) {
            heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0;
        }
        int currentArea = maximalHistogram(heights, matrixColSize[i]);
        if (currentArea > maxArea) {
            maxArea = currentArea;
        }
    }
    free(heights);
    return maxArea;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/601718.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

怎样通过PHP语言实现远程控制一路开关

怎样通过PHP语言实现远程控制一路开关呢&#xff1f; 本文描述了使用PHP语言调用HTTP接口&#xff0c;实现控制一路开关&#xff0c;一路开关可控制一路照明、排风扇等电器。 可选用产品&#xff1a;可根据实际场景需求&#xff0c;选择对应的规格 序号设备名称厂商1智能WiFi…

全面升级!一套基于Spring Boot 3+JDK17的实战项目!

最近把mall项目升级支持了Spring Boot 3JDK17&#xff0c;今天就来介绍下mall项目做了哪些升级&#xff0c;包括依赖的升级、框架的用法升级以及运行部署的改动&#xff0c;目前Spring Boot 3版本代码在mall项目的dev-v3分支下&#xff0c;希望对大家有所帮助&#xff01; mall…

压力测试-JMeter常用插件、服务器硬件监控

1.写在前面 在前一篇文章中&#xff0c;我们已经对jmeter有了一个入门的学习。 掌握了JMeter安装、入门、结果分析等内容&#xff0c;详情可查看这里&#xff1a;压力测试-JMeter安装、入门、结果分析 对于jmeter默认的插件&#xff0c;往往不太够&#xff0c;例如&#xff…

Python检查代码质量库之flake8使用详解

概要 Flake8是一个流行的Python库,用于检查代码质量和风格一致性,它集成了PyFlakes、pep8、Ned Batchelder的McCabe script等工具。Flake8可以帮助开发者发现代码中的错误,保持代码风格的一致性,是每个Python开发者工具箱中的重要组成部分。 安装 安装Flake8非常简单,可…

手把手教数据结构与算法:有序线性表设计(表合并)

个人主页&#xff1a; 想转码的电筒人 专栏&#xff1a; 手把手教数据结构与算法 文章目录 有序线性表 概念 结构 问题描述 输入 输出 样例 解题步骤 结点类 链表类 insert函数 printAll函数 merge函数 test函数 完整代码 有序线性表 概念 单链表是一种物…

《构建高效的财务管理系统:设计与实现》

在当今数字化时代&#xff0c;企业财务管理系统的设计与实现至关重要。一个高效的财务管理系统不仅能够提高企业的运营效率&#xff0c;还能够增强企业的竞争力&#xff0c;为企业的发展提供有力支持。本文将探讨财务管理系统的设计与实现&#xff0c;为企业打造一套符合自身需…

WEB应用防火墙:构建稳固的网络防线

随着互联网的飞速发展&#xff0c;WEB应用已成为企业对外展示形象、提供服务的重要窗口。然而&#xff0c;随之而来的是日益严峻的网络安全威胁&#xff0c;如跨站脚本攻击&#xff08;XSS&#xff09;、SQL注入、恶意文件上传等。为了保障WEB应用的安全&#xff0c;构建一套高…

AI智能分析赋能EasyCVR视频汇聚平台,为安全生产监管提供保障

一、背景需求 为提升公共及生产安全监管&#xff0c;深入贯彻落实中央关于智慧城市、数字乡村的部署要求&#xff0c;视频设备融合管理已成为视频治理的必然趋势。针对当前部分地区在视频监控系统建设中存在的问题&#xff0c;如重点地区视频监控系统建设零散、视频监控数据孤…

普通人适合做大模型吗?过程中会发生什么潜在的挑战?

对于普通人来说&#xff0c;直接进行大模型的研发和训练可能存在一定的挑战&#xff0c;因为这通常需要以下资源和知识&#xff1a; 专业知识&#xff1a; 大模型的开发需要深入理解机器学习、深度学习、神经网络等领域的知识。 计算资源&#xff1a; 大模型的训练需要高性能的…

数组元素翻倍C++

编写一个 C 程序&#xff0c;实现一个功能&#xff0c;即将数组中的每个元素值翻倍。程序应定义一个函数 doubleArray&#xff0c;该函数接收一个整数数组的指针和数组的大小&#xff0c;然后将数组中的每个元素都翻倍。 代码 #include <iostream>void doubleArray(int…

JSON++介绍

1.简介 JSON 是一个轻量级的 JSON 解析库&#xff0c;它是 JSON&#xff08;JavaScript Object Notation&#xff09;的一个超集。整个代码由一个单独的头文件json.hpp组成&#xff0c;没有库&#xff0c;没有子项目&#xff0c;没有依赖项&#xff0c;没有复杂的构建系统&…

安防视频/视频汇聚系统EasyCVR视频融合云平台助力智能化酒店安防体系的搭建

一、背景需求 2024年“五一”假期&#xff0c;全国文化和旅游市场总体平稳有序。文化和旅游部6日发布数据显示&#xff0c;据文化和旅游部数据中心测算&#xff0c;全国国内旅游出游合计2.95亿人次。“五一”假期县域市场酒店预订订单同比增长68%&#xff0c;而酒店作为一个高…

js原生手写一个拖拽小功能

先上效果图 附上代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta http-equiv"X-UA-Compatible" content"IEedge" /><meta name"viewport" content"widthd…

check startup检查各种资源文件

check startup 命令功能 check startup命令用来检查各种资源文件&#xff08;paf文件、补丁包、启动软件、配置文件&#xff09;是否正确。 命令格式 check startup [ crc ] [ next ] 参数说明 参数参数说明取值 crc 对资源文件进行CRC校验。 - next 检查下一次启动的各…

Git系列:Git Switch 高效使用技巧

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

用标准的GNU/Linux命令替换Alpine上的精简版命令

Alpine Linux 是一个基于 musl libc 和 busybox 的轻量级Linux发行版&#xff0c;busybox 实现了很多常用类Unix命令的精简版&#xff0c;特点是体积很小&#xff0c;舍弃了很多不常用参数&#xff0c;我们简单对比一下标准Linux自带的 date 命令 和 Alpine下默认的 date 命令便…

Golang | Leetcode Golang题解之第76题最小覆盖子串

题目&#xff1a; 题解&#xff1a; func minWindow(s string, t string) string {ori, cnt : map[byte]int{}, map[byte]int{}for i : 0; i < len(t); i {ori[t[i]]}sLen : len(s)len : math.MaxInt32ansL, ansR : -1, -1check : func() bool {for k, v : range ori {if c…

每日两题 / 138. 随机链表的复制 148. 排序链表(LeetCode热题100)

138. 随机链表的复制 - 力扣&#xff08;LeetCode&#xff09; 用哈希表记录原链表中的节点是否被复制过 遍历原链表并通过哈希表维护新链表 /* // Definition for a Node. class Node { public:int val;Node* next;Node* random;Node(int _val) {val _val;next NULL;rand…

Glowroot:Java应用的性能守护神,让监控变得既轻松又有趣!

Glowroot&#xff1a;Java应用的性能守护神&#xff0c;让监控变得既轻松又有趣&#xff01; 在这个快节奏的数字化时代&#xff0c;作为一名开发者&#xff0c;你是否曾因应用性能问题而夜不能寐&#xff1f;是不是常幻想有个超级英雄能在关键时刻挺身而出&#xff0c;帮你揪…

淘宝优惠券领取软件草柴返利APP想从淘宝粘贴提示怎么关闭?想从天猫粘贴、想从京东粘贴弹窗提示关闭

使用iPhone苹果手机想从淘宝点击分享复制链接&#xff0c;到草柴APP查询该商品内部大额隐藏优惠券和返利。可是&#xff0c;苹果iPhone手机每次将复制的商品链接&#xff0c;粘贴到草柴APP时都是提示&#xff1a;“草柴”想从“淘宝”粘贴&#xff0c;每次都需要点击允许粘贴后…
最新文章