动态规划算法(连续子数组最大和,O(N)时间复杂度O(1)空间复杂度) 【更新于:2018-05-13】

一篇文章读懂时间复杂度和空间复杂度 时间复杂度不计算时间,计算的是运算次数空间复杂度不计算空间,计算的是定义的变量个数。 阅读详情

这个题目最早在13年阿里笔试出现,直到前两天面试另一家电商又出现,哎,欠的都是要还的。

这个问题的思路如下:一维数组的下标连续的元素构成连续子数组,求所有连续子数组中和最大的那个子数组。

解析:2018-11-08

1 首先这个问题要转化为Q(n)的问题,对于Q(n)的问题要转化成Q(n) = Q(n-1) + An的问题。

2 只要能意识到这一点,其实就可以有希望在O(n)的时间内解决,不然,那就复杂的无法解决(因为你无法通过普通的循环遍历来做到,就算做到了,那复杂性也是难以承受的)。

3 上面的思想本质上还是一维动态规划算法。按照地归解分类讨论一下即可。

思路一旦确定,解的时候只需要更新各个临时变量和下标即可

解释(如上图所示):

1 Q(n)表示元素为n的数组其最优解(其下标范围为[i, j))

2 元素n+1为数组的第n+1个元素(其下标范围为n1)

3 A2为Q(n)产生时的一个子序列,这个序列的是Q(n)右侧和n+1之间的所有元素构成的集合,该序列的和一定是负值(下标范围为[j, n1))

4 A1为Q(n)产生时的Q(n)左侧的序列,该序列的和一定是负值

5 A1无需考虑,我们主要考虑加入第n+1元素时,新的Q(n+1)可能是那种情况即可。这里可能情况有四种。属于列举法解决问题。

6 首先考虑新的序列Q(n+1)会不会变的更长,也就是A2+(n+1)会不会也加入进来,这个是我们的直觉。这个时候会不会加进来主要看这个序列的和是不是大于零。也就是A2 + (n+1) > 0 ?  大于零也不是就一定要加上Q(n)。因为Q(n)可能是个负数,加了只会更小,这时候就不能加入,而A2又是和为负数,所以新的Q(n+1)只能是第n+1这个元素自己。这里的讨论只是以其中的一种情况为例讨论的。其余三种情况类似,参考上图即可。

7 本题的难点就在于列举出各种情况,很容易考虑不周,我就见过有人写的代码过于简单,考虑不周的。而且也写出来,这个是误人子弟(当然读者自己要去验证和辨别)

8 本题的第二个难点在于标记变量的设置和在各种情况下的更新。如果你把上图先画出来,对着图写程序,还是很简单的(即便这样,我的A2更新还是出过问题,改了两次才改好)。一定要严格定义上图中各个集合的范围,这时候他们在各种情况下的更新时机才会比较清晰,代码才不会写BUG。

代码:

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

int MaxSumOfContinuousSubSequence(const vector<int>& a, int& i, int& j)
{
	if (a.size() == 0)
	{
		throw "sequence must has one element at least!";
	}

	if (a.size() == 1)
	{
		return a[0];
	}
	//各个集合及其下标范围
	//Q(n)[i,j) 上一次的最优解与下标范围
	//A2[j,n1)  上一次的最优解与当前第n+1个元素之间的序列(A2各元素和总是负值)
	//n1[n+1,n+2)  当前Q(n+1)比Q(n)多出来的那个新元素
	i = 0;//Q(n)的起始下标
	j = 1;//A2的起始下标
	int n1 = 1;//n1的起始下标

	int currentMaxSum = a[0];
	int sumA2 = 0;

	for (n1 = 1; n1 < a.size(); ++n1)
	{
		if (sumA2 + a[n1] >= 0)
		{
			if (currentMaxSum > 0)
			{
				currentMaxSum = currentMaxSum + sumA2 + a[n1];
				sumA2 = 0;
				j = n1 + 1;
			}
			else
			{
				currentMaxSum = a[n1];
				sumA2 = 0;
				i = n1;
				j = n1 + 1;
			}
		} 
		else
		{
			if (currentMaxSum > a[n1])
			{
				currentMaxSum = currentMaxSum;
				sumA2 = sumA2 + a[n1];
			}
			else
			{
				currentMaxSum = a[n1];
				sumA2 = 0;
				i = n1;
				j = n1 + 1;
			}
		}
	}

	return currentMaxSum;
}

void test_max_sub_sum(const vector<int>& a)
{
	cout << "sequence ";
	for each (auto var in a)
	{
		cout << var << " ";
	}
	cout << endl;
	int begin, end;
	cout << "MaxSumOfContinuousSubSequence " << MaxSumOfContinuousSubSequence(a, begin, end) << endl;
	for (int i = begin; i < end; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl<<endl;
}

int main()
{
	vector<int>  a1 = { -1, 100, -200, 13};
	test_max_sub_sum(a1);

	vector<int>  a2 = { -1, 100, -200, 201};
	test_max_sub_sum(a2);

	vector<int>  a3 = { -1, 100, -200, 201, -20, -20, -20, 61};
	test_max_sub_sum(a3);

	vector<int>  a4 = { -1, 100, -200, 201, -20, -20, -20, 61, -104, 103};
	test_max_sub_sum(a4);

	vector<int>  a5 = { -1, 100, -200, 201, -20, -20, -20, 61, -104, 103, 1};
	test_max_sub_sum(a5);

	return 0;
}

输出:

 

 

 

 

华为OD机试 - 连续天数的最高利润额 - 动态规划(Python/JS/C/C++ 2024 C卷 100分) 刷的越多,抽中的概率越大,每一题都有详细的答题思路,详细的代码注释,发现新题目,随时更新。 阅读详情

相关推荐

RK3588视频转码实战:如何用FFmpeg+MPP实现16路1080P硬解压(附完整命令)

本文详细介绍了如何在RK3588处理器上使用FFmpeg和MPP框架实现16路1080P视频的硬件加速转码。通过解析RK3588的视频处理架构、环境搭建步骤和实战配置,提供了完整的命令示例和性能调优建议,帮助开发者高效处理多路视频转码任务。

weixin_29233333的博客 556

【算法】时间和空间复杂度

当我们谈论算法的效率时,我们关注的两个主要方面是时间复杂度和空间复杂度。时间复杂度描述的是算法在执行过程中所需要的时间资源。它通常用大O符号来表示,表示算法的运行时间随输入规模增大而变化的趋势。比如,O(1) 表示常数时间复杂度,O(n)表示线性时间复杂度,O(n^2)表示平方时间复杂度,等等。时间复杂度越低,算法的执行速度越快。空间复杂度描述的是算法在执行过程中所需要的内存资源。它也通常用大O符号来表示,表示算法的内存占用随输入规模增大而变化的趋势。

asd245025733的博客 2854

ESP32-P4开发板实战:从零配置VSCode环境到点亮MIPI-DSI屏幕(避坑指南)

本文详细介绍了ESP32-P4开发板在VSCode环境下的配置流程,包括SDK安装、idf_component.yml依赖管理,以及MIPI-DSI屏幕驱动的实现方法。通过实战指南帮助开发者避开常见配置陷阱,快速完成从环境搭建到屏幕点亮的全流程,适用于物联网和嵌入式开发场景。

pp12345的博客 741

动态规划背包问题优化空间复杂度——滚动数组

背包问题是动态规划中基本的问题,我们考虑下面的简单问题:   假设背包容量为4,有物品0,1,2,要使背包放的物品价值最大,并且总重量不超过背包容量,应该怎么放? 二维数组下的做法如下: 1、创建二维数组dp,其中dp[i][j]的含义是在0~i物品中任意取,放到容量为j的背包里,能够获得的最大价值。 2、确定递推公式 对于dp[i][j],假设不取第i个物品,那么dp[i][j]=dp[i-1][j];假设取第i的物品,那么dp[i][j]=dp[i-1][j-weight[...

qq_41523340的博客 1061

线性回归做糖尿病分析(diabetes数据集),并分析单个特征值与病情的关系

1.diabetes数据集 共442个样本,每个样本有十个特征,分别是 [‘age’, ‘sex’, ‘bmi’, ‘bp’, ‘s1’, ‘s2’, ‘s3’, ‘s4’, ‘s5’, ‘s6’],对应年龄、性别、体质指数、平均血压、S1~S6一年后疾病级数指标。 Targets为一年后患疾病的定量指标,值在25到346之间。 ...

t18438605018的博客 1万+

解密QtIFW高级配置:用XML+JS打造品牌化安装界面(含动态水印/多语言技巧)

本文深入探讨了如何利用Qt Installer Framework(QtIFW)的高级配置功能,通过XML和JavaScript打造专业、品牌化的软件安装界面。文章详细解析了企业级项目目录结构设计、模块化配置文件编写、CSS样式表深度定制、动态水印实现以及智能多语言许可证管理等核心技巧,旨在帮助开发者超越基础打包,为Windows和Linux平台构建具有卓越用户体验的安装程序。

read5的博客 528

连续子数组的最大和(动态规划时间复杂度o(n))

本题直接用原数组当做动态规划数组dp,以实现o(1)空间复杂度: JAVA: class Solution { public int maxSubArray(int[] nums) { int res=nums[0]; for(int i=1;i<nums.length;i++){ nums[i]=nums[i-1]<=0?nums[i]:(nums[i]+nums[i-1]); res=Math.max(nums[i],res...

qq_41884662的博客 364

软考29-上午题-【数据结构】-排序

数据结构7种排序

qq_31532983的博客 1579

[动态规划]最大子序列+最大子矩阵

一,最大子序列 所谓最大子序列,即元素和最大的连续子序列。  此次重点是动态规划, 所以其他方法就不说。 一切源于一个很容易理解但是很难想到的方程, 设b[i]表示以第i个元素a[i]结尾的最大子序列 b[i+1] = b[i]>0?(b[i]+a[i+1]):a[i+1]; 这样, 只要找出 数组b[]中的最大元素 即为最大子序列。 二,

404NotFound 542

物理机centos7系统重启后直接进入dracut

Warning: /dev/centos/root does not exist Warning: /dev/mapper/centos-root does not exist 在shell命令行执行以下: dracut:/# lvm vgscan dracut:/# lvm vgchange -ay dracut:/# exit 之后可以正常进入系统(测试正常)。 但是重启之后依然会进入dracut模式,永久解决如下: 查看kernel文件 [root@ecs ~]# ls -ltrh /boot

魏志标的博客 1万+

C#.NET斗地主服务端核心架构与高性能实现

斗地主作为典型的实时对战棋牌逻辑,本质是状态驱动的分布式协同问题。其技术内核涵盖有限状态机建模、低延迟网络同步、无GC内存操作与轻量级AI决策等关键能力。在.NET平台下,借助Span<T>、ImmutableArray、命令/事件总线与内存池等特性,可构建出高吞吐(200+ QPS)、低延迟(<150ms)、强一致的可落地服务端。本文聚焦C#.NET生态中斗地主核心模块的设计取舍与压测验证,深入解析状态机驱动、CardSet结构体优化、Kestrel中间件锁、规则+概率混合AI等实战方案,为实时对战类业务

weixin_29726381的博客 345

连续子数组的最大和

题目 输入一个整形数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组和的最大值。要求时间复杂度为O(n)。 例如,输入的数组为{1,-2,3,10,-4,7,2,-5},和最大的子数组为{3,10,-4,7,2},因此输出该子数组的和为18。 解题思路 从头到尾逐个累加示例数组中的每个数字。初始和为0。第一步加上第一个数字,此时和为1。第二步加上数字-2,和就变成了...

Hello World 201

哨兵1号后向散射系数土壤水分反演

打开之前预处理之后的VH和VV极化的后向散射系数转存的tiff文件。

所有专家都曾始于新手 3292

LeetCode-Hot100 13.最大子数组和

我们定义f[i]表示以nums[i]为结尾的最大子数组和。👉 为什么要「以nums[i]结尾」?子数组的核心要求是「连续」,固定结尾后,可通过前一个元素的状态推导当前状态(比如「以nums[i-1]结尾的最大子数组」加上nums[i],就能形成「以nums[i]结尾的子数组」,保证连续性)。前缀和preSum[i]表示数组前i个元素的和(,以此类推)。对于子数组nums[j..i](从第j个元素到第i动态规划的关键是「状态定义」—— 用「以当前元素结尾」的限定条件建立递推关系,化整为零;

2302_80987544的博客 1034

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

hot100-最大子数组和(day13)

dp[i]:以nums[i]为结尾的最大连续子数组和(必须包含 nums [i])。为什么这样定义?因为连续子数组的特性:以 nums [i] 结尾的子数组,要么是 nums [i] 本身,要么是「以 nums [i-1] 结尾的子数组」+ nums [i]解法时间复杂度空间复杂度核心思想适用场景暴力枚举O(n²)O(1)枚举所有子数组数组长度极小(n≤1e3)贪心算法O(n)O(1)舍弃负前缀,累加正贡献追求代码简洁、空间最优动态规划O(n)O(n)→O(1)

silver-kite的博客 1122

jre9下载 jdk9

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

【算法学习笔记】- 剑指OFFER 42题 连续子数组的最大和

描述 输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 数据范围: 1 <= n <= 10^51<=n<=10 5 -100 <= a[i] <= 100−100<=a[i]<=100 要求:时间复杂度为 O(n)O(n),空间复杂度为 O(n)O(n) 进阶:时间复杂度为 O(n)O(n),空间复杂度为 O(1)O(1) 参考: https://blog.nowcoder.net/n/b49b0

jackhh1的博客 651

深度学习工具包 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")

【Hot100|13-LeetCode53. 最大子数组和】

前缀和是关键:将子数组和问题转化为前缀和之差问题最小前缀和追踪:对于每个位置,最大子数组和 = 当前前缀和 - 之前的最小前缀和时间复杂度优化:从暴力解法的 O(n²) 优化到 O(n)

King_model的博客 781

求连续子数组的最大和

求连续子数组的最大和 整理自 http://blog.youkuaiyun.com/v_JULY_v/article/details/6444021 求子数组的最大和 题目描述: 输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。要求时间复杂度为O(n)。 例如输入的数组为1, -2, 3, 10

lwtb的博客 1171

python每日一题——13最大子数组和

python每日一题——13最大子数组和

WY_记录 567

LeetCode 热题 100_最大子数组和(13_53_中等_C++)(贪心算法 ||动态规划)

LeetCode 热题 100_最大子数组和(13_53_中等_C++) 题目描述: 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 子数组是数组中的一个连续部分。

huayimenghan的博客 617

连续数列-力扣

https://leetcode-cn.com/problems/contiguous-sequence-lcci/ 题目 给定一个整数数组,找出总和最大的连续数列,并返回总和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解 ...

qq_44918665的博客 579

连续子数组的和的最大值、最小值以及和的绝对值的最大值、最小值

连续子数组的和的最大值、最小值以及和的绝对值的最大值、最小值 标签: 子数组最小和绝对值最大和     http://blog.youkuaiyun.com/zuijinhaoma8/article/details/45290145 2015-04-26 17:30 527人阅读 评论(1) 收藏 举报 分类: leetcode/算法(13)

mmbbz的专栏 1457

hot 100 第十三题 13.最大子数组和

摘要:本文介绍了一种寻找数组中最大连续子数组和的算法。通过动态规划思想,在遍历数组时维护当前子数组和(currentSum)和全局最大和(maxSum)。对于每个元素,选择将其加入当前子数组或重新开始新的子数组(当currentSum为负数时)。时间复杂度O(n),空间复杂度O(1)。以示例[-2,1,-3,4,-1,2,1,-5,4]为例,算法最终找到最大和为6的子数组[4,-1,2,1]。该方法的有效性在于能及时舍弃负贡献的前缀和,确保找到全局最优解。

2401_87691507的博客 585

《数据结构实验指导-C++语言版》 连续子序列最大和

本文介绍了求解最大连续子序列和问题的Kadane算法。该算法通过一次扫描数组,动态维护当前子序列和及其起止下标,时间复杂度为O(n)。特别处理全非正数序列时输出0和-1下标。算法流程包括初始化、在线扫描更新和结果输出三个主要步骤,适用于大规模数据(n≤10^5)。代码实现简洁高效,通过比较当前和与新增元素的关系决定是否重置子序列起点,确保在最优解不唯一时输出最小下标组合。

冻柠茶飞冰走茶 200
上一篇: 【9】cpp_redis RapidJson redis (C++对象利用Rapidjson序列化到redis与反序列化)
下一篇: MFC滚动条自动对齐:一个grid选中一行另一个grid也选中相同行并且内容和滚动条自动对齐
C++程序员Carea
博客等级 码龄18年 1590粉丝 878原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值