子矩阵的最大累加和

LeetCode085子矩阵最大累加和(相关话题:前缀和,动态规划) 前缀和,动态规划思想 阅读详情
题目:给定一个矩阵matrix,其中的值有正、有负、有零,返回子矩阵的最大累加和。例如矩阵matrix为:
  -90 48 78
  64 -40 64
  -81 -7 66
其中,最大累加和的子矩阵为:
  48 78
  -40 64
  -7 66
所以返回子矩阵的最大累加和为209。
    解析:最简单也最容易想到的方法是求出矩阵中的所有子矩阵,随后计算每个子矩阵的累加和,该方法的时间复杂度为O(n^4),因为一个矩阵中子矩阵的个数是n^4级别。之前介绍过连续子数组的最大和,求子矩阵的最大累加和问题实际上就是连续子数组问题的扩展,从一维空间转换为二维空间,我们可以把子矩阵的最大累加问题分解为求连续子数组的最大累加和,例如一个M*N的矩阵可以分解为M个一维矩阵,M-1个二维矩阵,M-i个i+1维矩阵等等,二维矩阵行相加又可以转为一维矩阵,同理,其他维矩阵都可以转为一维矩阵。随后在转换后的一维数组中求出连续子数组的最大和,在所有连续子数组的最大和中选择一个最大值即为子矩阵的最大累加和。该算法的时间复杂度为O(n^2*m)。代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//连续子数组的最大和
int subArrMaxSum(vector<int> &arr)
{
	int max_sum = INT_MIN;
	int sub_max_sum = 0;
	for (int i = 0; i < arr.size(); ++i)
	{
		sub_max_sum += arr[i];
		if (sub_max_sum < 0)
		{
			sub_max_sum = 0;
		}
		if (sub_max_sum > max_sum)
		{
			max_sum = sub_max_sum;
		}
	}
	return max_sum;
}

//子矩阵的最大累加和
int subMatixMaxSum(vector<vector<int>> &matrix)
{
	if (matrix.empty())
		return 0;
	int rows = matrix.size();
	int cols = matrix[0].size();
	int max_sum = INT_MIN;
	int sub_max_sum = 0;
	for (int row = 0; row < rows; ++row)
	{
		vector<int> arr(cols);
		for (int i = row; i < rows; ++i)
		{
			for (int col = 0; col < cols; ++col)
			{
				arr[col] += matrix[i][col];
			}
			sub_max_sum = subArrMaxSum(arr);
			if (sub_max_sum > max_sum)
			{
				max_sum = sub_max_sum;
			}
		}
	}
	return max_sum;
}

int main(void)
{
	vector<vector<int>> matrix = {
		{ 0,-2,-7,0 },
		{ 9,2,-6,2 },
		{ -4,1,-4,1 },
		{-1,8,0,-2}
	};
	cout << subMatixMaxSum(matrix) << endl;
	system("pause");
	return 0;
}
最大连续子矩阵累加和 在此之前我们先做个铺垫:最大连续和:  题目大意:给定n个数,求这些数的某个连续子序列的累加和,保证这个连续子序列的累加和最大。  举个栗子(俗称样例):  输入:7 -3 4 9 -2 -5 8 -3  输出:  14样例解释:最大的呢是:4+9+(-2)+(-5)+8由此可见,无法将加上当前数的和与当前最大值进行对比来确定答案,虽然有负数,但之后可能有更大的数,即可以弥补加上的负数,还可以增大... 阅读详情

相关推荐

【算法】子矩阵的最大累加和

一、题目描述 给定一个矩阵matrix,其中的值有正、负、0,返回子矩阵的最大累加和。 例如: 输入: -1 -1 -1 -1 2 2 -1 -1 -1 输出: 4 (其中最大累加和的子矩阵为:2 2) 二、思路及其代码实现 思路: A、分别以第i行为起始行: (1)按列累加第i行,得到列累加一维数组,则第i行子矩阵的最大子矩阵和 = 一维数组的最大累加和; (2)按列累加第i行和第i+1行,...

m0_46204129的博客 298

子矩阵最大累加和(详解)

题目:给定一个矩阵matrix,其中的值有正,有负,有0,返回子矩阵的最大累加和 例:matrix为: -1 -1 -1 -1  2  2 -1 -1 -1 其中最大累加和的子矩阵为 2 2 所以返回4. 分析思路: 下面有方框圈出来的类似这种的都是子矩阵 刚开始考虑用暴力解法 将每一个定点都进行遍历找子矩阵,虽然可行,但是它的时间复杂度会非常高0(n^4)。 改进算...

gl620321的博客 1153

解决2020R2,2022R1等版本的SCDM无法编辑草图尺寸的问题

解决2020R2,2022R1等版本的SCDM无法编辑草图尺寸的问题

y_u_yu_yu_的博客 1万+

算法入门_求最大连续子列和的四种解法

算法入门_求最大连续子列和的四种解法 文章目录算法入门_求最大连续子列和的四种解法@[toc]0.简介1.算法一:暴力运算累加2.算法二:选择排序累加3.算法三:分而治之4.算法四:在线处理 0.简介 ​ 刚开始学算法(看视频),遇到个入门算法问题:求最大连续子列的和。 #include<stdio.h> #include<string.h> int MaxContiS...

qq_35289660的博客 612

scGPT实战指南:如何用生成式AI加速你的单细胞多组学研究?

本文提供了scGPT在单细胞多组学研究中的实战指南。详细介绍了从环境部署、数据预处理到细胞类型注释与扰动预测等核心任务的操作流程。通过利用生成式AI和Transformer基础模型,scGPT能够显著加速分析,并提升细胞注释的准确性及基因调控网络推断的深度,为研究人员提供了强大的AI分析引擎。

weixin_29215815的博客 408

从零解析:富斯i6遥控器与STM32的IBUS协议通信实战

本文详细解析了富斯i6遥控器与STM32通过IBUS协议通信的实战指南,涵盖硬件准备、协议解析、驱动实现及常见问题解决。特别适合机器人及智能小车开发者,提供低成本、高可靠性的无线控制方案,助力快速实现多通道控制功能。

weixin_29193359的博客 444

子矩阵的最大累加和问题

子矩阵的最大累加和问题 题目描述 给定一个矩阵matrix,其中的值有正、有负、有0,返回子矩阵的最大累加和 例如,矩阵matrix为: -90 48 78 64 -40 64 -81 - 7 66 其中,最大的累加和的子矩阵为: 48 78 -40 64 -7 66 所以返回累加和209。 例如,matrix为: -1 -1 -1 -1 2 2 -1 -1 -1 其中,最大累加和的子矩阵为: 2 2 所以返回4 [要求] 时间复杂度为O(n2m)O(n^2m)O(n2m),空间复杂度为O(nm)O(nm)

MIC10086的博客 200

PDMS二次开发(十四)——自动插入焊口和计算焊接当量(达因数)

Pipeline Tool增加新功能:自动添加焊口并计算焊接当量(达因数),Pipeline大版本号升为0.9.5。

天堂向左 4578

子矩阵最大累加和

遍历行的组合,将多行元素融合成一行用一维数组最大累加和的方法计算

月巴虫丰博客 487

RAG——RAG 索引(文档解析技术)

本文介绍了RAG系统中文档解析的关键技术,重点分析了如何通过LangChain的Document Loaders处理多种格式文档。文章指出高质量文档解析对RAG系统效果的决定性作用,并详细讲解了PDF、TXT、Word等常见格式的解析方法。作者提供了代码示例和Gitee开源项目链接,特别强调了PDF解析的深入方案,同时介绍了相关依赖库的安装配置。文章还展示了如何定义通用文档加载方法,为开发者提供了实用的技术参考。

小志的博客 768

落地实战!Python构建地方政府公开数据爬虫:政策/数据/规划全维度抓取(附反爬适配+数据清洗)

政务公开数据爬虫的核心不是“技术多先进”,而是“适配政务网站的特性”——慢一点、稳一点、合规一点,比追求抓取速度更重要。多地市爬虫集群:通过配置文件管理不同地市的URL规则,实现全省/全国政务数据抓取;图片表格识别:结合OCR工具(如pytesseract)识别政务网站的图片表格,转换为结构化数据;数据可视化:将抓取的统计数据导入PowerBI/Matplotlib,实现区域发展趋势分析。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1808

子数组的最大累加和问题与子矩阵的最大累加和问题(java)实现

题目: 1.给定一个数组array,返回子数组的最大累加和。 例如:array=[1,-2,3,5,-2,6,-1],所有的子数组中,[3,5,-2,6]累加出的和最大,为12,所以返回12. 分析: 本题要遍历数组,毫无疑问。但核心在于该如何正确的遍历数组来得到累加和最大的子数组? 解决:从左到右遍历array,用count记录每一步的累加和,若遍历到正数,count增加,若遍历到负数,coun...

weixin_42373873的博客 446

【数据分享】12.5米分辨率DEM地形数据(分省)

该数据来源于NASA地球科学数据网站(https://nasadaacs.eos.nasa.gov/),是ALOS卫星获取的高精度地形数据。该数据由于精度高,包括全省范围的数据和省内每个城市范围的数据!

JData_Engineer的博客 2186

蓝桥杯——子矩阵的最大累加和

题目描述:给定一个矩阵matrix,其中有正、有负、有0,返回子矩阵的最大累加和。 例如,matrix为: {{-1,-1,-1}, {-1 , 2 , 2}, {-1,-1,-1}} 其中最大累加和的子矩阵为: 2,2 所以返回4 解题思路 这道题的关键在于必须是子矩阵,而子矩阵的情况太多了,如果一一列举的话想必是不能达到要求的。所以这道题需要对原二维数组(矩阵)进行一些预处理,也就是降维...

weixin_43408112的博客 230

使用Simulink设计并实现一个可调谐的二阶IIR陷波滤波器,实时去除音频中的工频噪声

《基于Simulink的音频陷波滤波器设计与实现》摘要:本文详细介绍了使用Simulink设计陷波滤波器去除音频工频噪声(如50Hz)的方法。核心内容包括:1)二阶IIR陷波滤波器的原理与传递函数;2)Simulink实现步骤(音频系统搭建、滤波器设计、频率跟踪);3)性能分析(频谱对比、时域波形、听觉测试)。通过精准消除特定频率干扰,同时保留语音信号(200Hz-4kHz),有效提升信噪比(>20dB)。文章还探讨了多陷波级联、自适应算法等高级技巧,为音频处理、语音通信等应用提供实用解决方案。

amy_mhd的博客 163

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

求累加和小于等于k的最大子矩阵

来自牛客网左程云第三课第二题 问题:给定一个无序矩阵,其中有正,有负,有 0,再给定一个值 k,求累加和小于等于 k 的最大子矩阵大小,矩阵的大小用其中的元素个数来表示。 分析:这个问题也是一个子矩阵问题,参看求子矩阵的最大和的分析,我们同样可以将其转换成子数组问题。本题的算法原型是未排序数组中累加和小于或等于给定值的最长子数组长度。 解法:我们求出以每一行的为首行的子矩阵的列累加和,就是将

穷理何须格物的博客 1507

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

子矩阵最大累加和——算法笔记

假定只有一行,那就和求最大和子数组一样 如果限定两行,可以把两行按列求和,同上 所以我们以第一行当做起点,依次累加后面的每一行后,都求一个最大子数组和 以第二行作为起点,依次累加后面的每一行后,都求一个最大子数组和 每次求出来的和与历史最大值比较,如果更大,则更新 N^3时间复杂度 #include <iostream> #include <cstring> using...

GaoJuno23的博客 358

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

算法题解:子矩阵的最大累加和问题(JAVA代码)

算法题解:子矩阵的最大累加和问题(JAVA代码) 给定一个n*m的矩阵A,求A中的一个非空子矩阵,使这个子矩阵中的元素和最大。 其中,A的子矩阵指在A中行和列均连续的一块。 输入样例 -1 -4 3 3 4 -1 -5 -2 8 样例输出 10 说明:最后一列子矩阵和累加为 3+(-1)+8 = 10 输入样例 -90 ...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 1318

算法总结之 子矩阵的最大累加和问题

算法总结之 子矩阵的最大累加和问题 给定一个矩阵matrix, 其中的值有正 负 0 ,返回子矩阵的最大累加和 这个是 子数组最大累加和问题的 升级版 看例子就懂了: 如果只有两行,那么 上下两行相加,得出列加数组 得出最大累加和 总结整个过程,关键之处在于: 用求累加数组的最大累加和是的的方式得...

art_code的博客 573

经典算法——子矩阵的最大累加和问题

一、题目要求 给定一个矩阵matrix,其中的值有正有负,有0,返回子矩阵的最大累加和,例如,矩阵matrix为: -90 48 78 64 -40 64 -81 07 66 其中,最大累加和的子矩阵为: 48 78 -40 64 -7 66 所以返回累加和209 二、解题思路 将矩阵matrix[N][N]的每一列的N个元素累加成一个累加数组,然后求出这个数

henryzhihua 3454
上一篇: 矩阵中最长连续递增子序列
下一篇: 主机字节序大端和小端
yang20141109
博客等级 码龄12年 80粉丝 167原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值