363. Max Sum of Rectangle No Larger Than K

Java实现 LeetCode 363 矩形区域不超过 K 的最大数值和 363. 矩形区域不超过 K 的最大数值和 给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k 的最大矩形和。 示例: 输入: matrix = [[1,0,1],[0,-2,3]], k = 2 输出: 2 解释: 矩形区域 [[0, 1], [-2, 3]] 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。 说明: 矩阵内的矩形区域面积必须大于 0。 如果行数远大于列数,你将如何解答呢? class Solution { public static int maxSumSubmatrix(int[][] matrix, int k) { 立即下载

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

Example:

Given matrix = [
  [1,  0, 1],
  [0, -2, 3]
]
k = 2

The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2).

Note:

  1. The rectangle inside the matrix must have an area > 0.
  2. What if the number of rows is much larger than the number of columns?

Credits:

Special thanks to @fujiaozhu for adding this problem and creating all test cases.



摘自

https://discuss.leetcode.com/topic/48875/accepted-c-codes-with-explanation-and-references/4

http://www.cnblogs.com/fll/archive/2008/05/17/1201543.html


先看一下最大子矩阵问题。


给定一个n*n(0<n<=100)的矩阵,请找到此矩阵的一个子矩阵,并且此子矩阵的各个元素的和最大,输出这个最大的值。
Example:
 0 -2 -7  0 
 9  2 -6  2 
-4  1 -4  1 
-1  8  0 -2 
其中左上角的子矩阵:
 9 2 
-4 1 
-1 8 
此子矩阵的值为9+2+(-4)+1+(-1)+8=15。
  我们首先想到的方法就是穷举一个矩阵的所有子矩阵,然而一个n*n的矩阵的子矩阵的个数当n比较大时时一个很大的数字 O(n^2*n^2),显然此方法不可行。
  怎么使得问题的复杂度降低呢?对了,相信大家应该知道了,用动态规划。对于此题,怎么使用动态规划呢?

  让我们先来看另外的一个问题(最大子段和问题):
    给定一个长度为n的一维数组a,请找出此数组的一个子数组,使得此子数组的和sum=a[i]+a[i+1]+……+a[j]最大,其中i>=0,i<n,j>=i,j<n,例如
   31 -41 59 26 -53  58 97 -93 -23 84
 子矩阵59+26-53+58+97=187为所求的最大子数组。
第一种方法-直接穷举法:
   maxsofar=0;
   for i = 0 to n
   {
       for  j = i to n 
       {
            sum=0;
            for k=i to j 
                sum+=a[k] 
            if (maxsofar>sum)
               maxsofar=sum;
       }
   }

第二种方法-带记忆的递推法:
   cumarr[0]=a[0]
   for i=1 to n      //首先生成一些部分和
   {
        cumarr[i]=cumarr[i-1]+a[i];       
   }

   maxsofar=0
   for i=0 to n
   {
       for  j=i to n     //下面通过已有的和递推
       {
           sum=cumarr[j]-cumarr[i-1]
           if(sum>maxsofar)
               maxsofar=sum
       }
   }
显然第二种方法比第一种方法有所改进,时间复杂度为O(n*n)。

下面我们来分析一下最大子段和的子结构,令b[j]表示从a[0]~a[j]的最大子段和,b[j]的当前值只有两种情况,(1) 最大子段一直连续到a[j]  (2) 以a[j]为起点的子段,不知有没有读者注意到还有一种情况,那就是最大字段没有包含a[j],如果没有包含a[j]的话,那么在算b[j]之前的时候我们已经算出来了,注意我们只是算到位置为j的地方,所以最大子断在a[j]后面的情况我们可以暂时不考虑。
由此我们得出b[j]的状态转移方程为:b[j]=max{b[j-1]+a[j],a[j]},
所求的最大子断和为max{b[j],0<=j<n}。进一步我们可以将b[]数组用一个变量代替。
得出的算法如下:
    int maxSubArray(int n,int a[])
    {
        int b=0,sum=-10000000;
        for(int i=0;i<n;i++)
        {
             if(b>0) b+=a[i];
             else b=a[i];
             if(b>sum) sum=b;  
        }
        return sum;
    }
这就是第三种方法-动态规划。


  现在回到我们的最初的最大子矩阵的问题,这个问题与上面所提到的最大子断有什么联系呢?
  假设最大子矩阵的结果为从第r行到k行、从第i列到j列的子矩阵,如下所示(ari表示a[r][i],假设数组下标从1开始):
  | a11 …… a1i ……a1j ……a1n |
  | a21 …… a2i ……a2j ……a2n |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ar1 …… ari ……arj ……arn |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ak1 …… aki ……akj ……akn |
  |  .     .     .    .    .     .    .   |
  | an1 …… ani ……anj ……ann |

 那么我们将从第r行到第k行的每一行中相同列的加起来,可以得到一个一维数组如下:
 (ar1+……+ak1, ar2+……+ak2, ……,arn+……+akn)
 由此我们可以看出最后所求的就是此一维数组的最大子断和问题,到此我们已经将问题转化为上面的已经解决了的问题了。

此题的详细解答如下(Java描述):

import java.util.Scanner;
public class PKU_1050
{
     private int maxSubArray(int n,int a[])
      {
            int b=0,sum=-10000000;
            for(int i=0;i<n;i++)
            {
                  if(b>0) b+=a[i];
                  else b=a[i];
                  if(b>sum) sum=b;
            }
            return sum;  
      }
      private int maxSubMatrix(int n,int[][] array)
      {
            int i,j,k,max=0,sum=-100000000;
            int b[]=new int[101];
            for(i=0;i<n;i++)
            {
                  for(k=0;k<n;k++)//初始化b[]
                  {
                        b[k]=0;
                  }
                  for(j=i;j<n;j++)//把第i行到第j行相加,对每一次相加求出最大值
                  {
                        for(k=0;k<n;k++)
                        {
                              b[k]+=array[j][k];
                        }
                        max=maxSubArray(k,b);  
                        if(max>sum)
                        {
                                sum=max;
                        }
                  }
            }
            return sum;
      }
      public static void main(String args[])
      {
            PKU_1050 p=new PKU_1050();
            Scanner cin=new Scanner(System.in);
            int n=0;
            int[][] array=new int[101][101];
            while(cin.hasNext())
            {
                       n=cin.nextInt();   
                       for(int i=0;i<n;i++)
                       {
                                  for(int j=0;j<n;j++)
                                  {
                                             array[i][j]=cin.nextInt();
                                  }
                       }
                       System.out.println(p.maxSubMatrix(n,array));
            }
      }
}



这里有限制,和不能超过K,又要最接近,参考问题


find a subarray that contains the largest sum, constraint that sum is less than k


把一维当中求最大子序列和替换为这个问题的解,2维到1维的处理过程不变。

public int maxSumSubmatrix(int[][] matrix, int k) {
    //2D Kadane's algorithm + 1D maxSum problem with sum limit k
    //2D subarray sum solution
    
    //boundary check
    if(matrix.length == 0) return 0;
    
    int m = matrix.length, n = matrix[0].length;
    int result = Integer.MIN_VALUE;
    
    //outer loop should use smaller axis
    //now we assume we have more rows than cols, therefore outer loop will be based on cols 
    for(int left = 0; left < n; left++){
        //array that accumulate sums for each row from left to right 
        int[] sums = new int[m];
        for(int right = left; right < n; right++){
            //update sums[] to include values in curr right col
            for(int i = 0; i < m; i++){
                sums[i] += matrix[i][right];
            }
            
            //we use TreeSet to help us find the rectangle with maxSum <= k with O(logN) time
            TreeSet<Integer> set = new TreeSet<Integer>();
            //add 0 to cover the single row case
            set.add(0);
            int currSum = 0;
            
            for(int sum : sums){
                currSum += sum;
                //we use sum subtraction (curSum - sum) to get the subarray with sum <= k
                //therefore we need to look for the smallest sum >= currSum - k
                Integer num = set.ceiling(currSum - k);
                if(num != null) result = Math.max( result, currSum - num );
                set.add(currSum);
            }
        }
    }
    
    return result;
}


用户行为数据分析 User Behavior Data from Taobao for Recommendation 一、提出问题 二、理解数据 数据来源 阿里云天池数据集:(https://tianchi.aliyun.com/dataset/dataDetail?dataId=649) 本文选取的数据集为UserBehavior.csv,共有5242880条数据。数据的具体类别如下表所示: 用户行为种类有四种,如下表所示 对于数据维度的说明如下: 在本文选取的2017年11月25日到2017年12月3日的时间范围内,不重复的用户数量为10202,不重复的商品ID数为412369,不重复的商品类目ID数为5859, 阅读详情

相关推荐

汇川PLC程序框架设计:模块化分层与标准化实践指南

在工业自动化领域,可编程逻辑控制器(PLC)是设备控制的核心大脑。其编程质量直接决定了系统的稳定性、可维护性与开发效率。遵循高内聚、低耦合的软件工程原则,通过模块化分层设计,能够将复杂的控制逻辑分解为硬件驱动、设备控制、流程管理等清晰层级,并利用功能块(FB)封装可复用的设备控制逻辑。这种结构化方法的技术价值在于大幅提升代码的可读性、可测试性与团队协作效率,有效降低后期维护与功能迭代的难度。其应用场景广泛覆盖从单机设备到复杂产线的自动化项目。本文聚焦于汇川PLC平台,深入探讨如何构建一套融合了**状态机编程

weixin_29188997的博客 401

Leetcode刷题笔记 363 矩形区域不超过 K 的最大数值和

给你一个m×n的矩阵 matrix 和一个整数k,找出并返回矩阵内部矩形区域的不超过k的最大数值和。题目数据保证总会存在一个数值和不超过 k 的矩形区域。

qq_43796795的博客 301

【开源数据集】电动车佩戴头盔检测数据集(TWHD)

佩戴头盔检测数据集VOC格式图像与标注数量各5448张

hzg19930513的博客 5168

[LeetCode]Maximal Rectangle

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 动态规划 用left[ ]数组纪录该点距离最左边(在矩形内部)的1的距离,用right[ ]数组纪录该点距离最右边(在矩形内部)的1距离,height[ ]

大力拜 654

雾化器硬件设计:从N155驱动到PCB可量产实现

雾化器是典型的机电一体化嵌入式终端,其硬件设计本质是电源完整性、信号完整性与热-机械协同的系统工程。核心在于理解高压脉冲驱动原理(如2.4MHz固定频率匹配压电谐振)、电源域隔离机制(AGND/DGND/PGND分域设计)及约束驱动的PCB转化逻辑。技术价值体现在电气可靠性(如OTP/OLP保护)、生产可制造性(DFM合规焊盘与钢网)与环境鲁棒性(三防漆、散热过孔)。典型应用场景覆盖加湿器、医疗雾化仪与工业微流控设备。本文聚焦超声波雾化控制板的硬线实现路径,深入解析N155驱动芯片选型、网络标签工程误用陷阱

weixin_35649491的博客 617

优化Cartographer重定位速度:从子图筛选到参数调优的完整思路

本文详细介绍了优化Cartographer重定位速度的完整方法,从子图筛选到参数调优,帮助工程师在已知初始位姿的前提下将重定位耗时降低50%以上。重点分析了性能瓶颈、子图筛选策略、匹配算法选择及环境自适应的参数优化策略,并通过实战案例展示了显著效果提升。

weixin_28704565的博客 463

leetcode 85. Maximal Rectangle(最大矩形)

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area. Example: Input: [ [“1”,“0”,“1”,“0”,“0”], [“1”,“0”,“1”,“1”,“1”], [“1”,“1”,“1”,“1”,“...

蓝羽飞鸟的博客 161

STM32+ESP8266接入OneNet的MQTT嵌入式实现

MQTT是一种轻量级发布/订阅模式的消息传输协议,广泛应用于资源受限的物联网终端设备通信。其基于TCP/IP栈构建,具备低带宽占用、小代码体积和高可靠性等技术优势,特别适合STM32等MCU与Wi-Fi模组协同工作的边缘节点场景。在实际工程中,需结合AT指令集控制ESP8266完成Wi-Fi连接、TCP建链及MQTT会话管理,并通过环形缓冲区、空闲中断检测等机制保障UART异步通信稳定性。本文围绕STM32F103与ESP8266硬件协同、OneNet平台对接、JSON消息解析与OLED状态反馈等关键环节,

yhn456789的博客 1036

[leetcode] 363. Max Sum of Rectangle No Larger Than K 解题报告

题目链接: https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/ Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is

小榕流光的专栏 7088

2025虚幻游戏逆向工程解包尝试

2025虚幻游戏逆向工程解包指南 本文详细介绍了虚幻引擎5游戏逆向解包的完整流程,主要包括获取AES密钥、生成映射文件和导出资源三个关键步骤。作者在实际操作中遇到诸多难题:AES密钥获取工具存在加壳保护问题,映射文件生成器依赖复杂的VS编译环境,DLL注入工具的使用也存在技术门槛。通过多次尝试,作者发现部分游戏可直接搜索现成的AES密钥,而映射文件生成需要额外下载Memcury依赖库才能正常编译。文章提供了相关工具的下载链接和具体操作说明,但同时也指出每个环节都可能出现意外状况,逆向工程实际执行过程远比理论

wsdchong的博客 6150

单智能体篇:Prompt工程艺术

模型在接收到 Prompt 时会自动扮演“角色”,角色定义的好坏直接影响智能体输出的风格和专业性。角色定义的重要性让智能体具备明确身份,例如“你是一位专业理财顾问”或“你是一个幽默的文案创作助手”。角色限定了模型知识输出的范围,使回答更专业、更贴合预期。实战示例模糊Prompt给我一些投资建议。你可以投资股票或者基金。优化Prompt你是一位具有10年经验的专业理财顾问,请给我针对30岁男性,年收入20万,风险偏中等的投资组合建议。

公众号:AI前沿侦探 1304

363. Max Sum of Rectangle No Larger Than K ,由之引申出的三个问题

363. Max Sum of Rectangle No Larger Than K ,由之引申出的三个问题 目录 363. Max Sum of Rectangle No Larger Than K ,由之引申出的三个问题 目录 最大连续子数组和 &amp;amp;amp;amp;amp;lt;=k最大子数组和 2d到1d的转化 本Markdown编辑器使用[StackEdit][6]修改而来,用它写博...

qq_24436311的博客 285

[leetcode] 363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k. Example: Given matrix = [ [1, 0, 1], [0, -2, 3] ] k

TstsUgeg的博客 1312

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode 363. Max Sum of Rectangle No Larger Than K(矩阵和)

原题网址:https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/ Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is

James Pan 4109

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

【leetcode】363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k. Example: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: ...

ghscarecrow的博客 273

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrixmatrixand an integerk, find the max sum of a rectangle in thematrixsuch that its sum is no larger thank. Example: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2...

李歇特冯-兹拜因巴哈的博客 169

leetcode 363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrixmatrixand an integerk, find the max sum of a rectangle in thematrixsuch that its sum is no larger thank. Example: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: ...

PaladinDu的专栏 186

Leetcode 363. Max Sum of Rectangle No Larger Than K

对于一维数组,求每个数从数组第一个元素开始的累计和sum[i],对于每一个数num[i]而言,要找到sum[i] - sum[j]<=k,且sum[j]最小的数,用java Treemap进行二分查找即可。 而二维数组,可以进行遍历,将相同列的数累加,转换成一维数组的形式。 解决row>column的方式:按照列的方式进行累加和的计算以及二分查找。 class Solution { public int maxSumSubmatrix(int[][] matrix, i...

I_ren的博客 244

LeetCode //C - 363. Max Sum of Rectangle No Larger Than K

【代码】LeetCode //C - 363. Max Sum of Rectangle No Larger Than K。

Made in Code 1083

leetcode.363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k. Example: Given matrix = [ [1, 0, 1], [0, -2, 3] ] k

happyxuma1991的博客 477

[LeetCode 363] Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrixmatrixand an integerk, find the max sum of a rectangle in thematrixsuch that its sum is no larger thank. Example: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output:...

ExcitedZhang的博客 145
上一篇: find a subarray that contains the largest sum, constraint that sum is less than k
下一篇: 368. Largest Divisible Subset
wdlsjdl2
博客等级 码龄15年 4粉丝 246原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值