Leetcode:最大子序和(java)

贪心算法在LeetCode中的应用:分发饼干、摆动序列和最大子序和(Java实现) 通过以上的贪心算法的应用示例,我们可以看到贪心算法的简单而高效的特点。因此,在应用贪心算法时,我们需要仔细分析问题的特点,并确保贪心策略的正确性。贪心策略:我们可以先对孩子的胃口值和饼干的大小进行排序,然后从胃口值最小的孩子和大小最小的饼干开始匹配。在本文中,我们将探讨三个典型的使用贪心算法的问题:分发饼干、摆动序列和最大子序和,并提供相应的Java代码实现。问题描述:给定一组孩子的胃口值和一组饼干的大小,其中每个孩子有一个胃口值,用于表示他们对饼干大小的需求程度。希望本文对你理解贪心算法的应用有所帮助。 阅读详情

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:

如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
package LeetCode;


public class MaxSubArray {
    public int maxSubArray(int[] nums) {
        //最大值设为最小值
        int max=Integer.MIN_VALUE;
        //累加初始值为0
        int num=0;
        for (int i = 0; i <nums.length ; i++) {
            //每一个值先加入到累加值中
          num+=nums[i];
          //判断累加值和最大值的大小
          if (num>max){
              //大的话把累加值赋给最大值
              max=num;
          }
          //从正整数的开始进行增加
          if (num<0){
              num=0;
          }
        }
        return max;
    }

    public static void main(String[] args) {
        MaxSubArray a=new MaxSubArray();
        int[] b={-2,1,-3,4,-1,2,1,-5,4};
        System.out.println( a.maxSubArray(b));
    }
}

 

3种方法求 最大连续子序列和 解法1—O(N^2)解法 解法2—O(NlgN)解法 解法3—O(N)解法 可以直接在记事本运行 立即下载

相关推荐

k8s部署 普罗米修斯(Prometheus)监控

Prometheus是一个开源的服务监控系统和时序数据库其提供了通用的数据模型和快捷数据采集、存储和查询接口它的核心组件Prometheus服务器定期从静态配置的监控目标或者基于服务发现自动配置的目标中进行拉 取数据新拉取到啊的 数据大于配置的内存缓存区时,数据就会持久化到存储设备当中。

D2961953033的博客 3863

java实现子序列最大和_算法入门:最大子序列和的四种算法(Java)

最近再学习算法和数据结构,推荐一本书:Data structures and Algorithm analysis in Java 3rd以下的四种算法出自本书 四种最大子序列和的算法:问题描述给定(可能有负数)整数a(1)、a(2)、……a(n),求 a(1)+a(2)+……+a(j)的最大值。为方便起见,若所有的整数为负数,则最大子序列和为0.也就是:在一系列整数中,找出连续的若干个整数,这若...

weixin_29119475的博客 3539

别再瞎猜了!Fluent瞬态计算时间步长到底设多少?一个公式+实战案例搞定

本文详细解析了Fluent瞬态计算中时间步长的设置方法,通过黄金公式和实战案例,帮助工程师准确确定时间步长,避免计算发散和资源浪费。文章还介绍了动态调整策略和典型工程场景的参数优化,提升仿真效率和精度。

weixin_42638178的博客 430

最大子序和(Java实现)

问题描述: 给定一个整数数组nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释:连续子数组[4,-1,2,1] 的和最大,为6。 解题思路: 方法一:采用粗暴的方法,先固定一个开头元素,然后往后遍历,依次增加子序列的元素,并且求和,然后与最大值作比较,保留新的最...

weixin_43573824的博客 459

储能EMS工作原理深度剖析:功率分配与充放电策略的底层逻辑

储能EMS的功率分配与充放电策略,是其智能化的集中体现。功率分配更像一个“执行指挥官”,关注如何将总任务高效、公平、安全地分解到每个士兵(PCS/电池簇);而充放电策略则像“总参谋长”,基于战场情报(市场、电网、自身状态)制定最优的作战计划。AI强化学习策略:让EMS通过与复杂环境不断交互,自主学习最优策略,适应不确定性。数字孪生与仿真:在虚拟空间中提前验证策略,评估风险,实现预防性控制。跨站协同优化:多个储能站的EMS通过云平台协同,参与区域电网甚至跨省市场的联合优化调度。

小帽子的博客 382

SAP_PP模块跑完 MRP,MD04 里却看不到“计划订单”?排查这 3 个最容易被忽略的主数据参数

MRP 是 SAP 逻辑最严密的模块之一,它绝不会随机罢工。当 MD04 里看不到计划订单时,请不要怀疑系统的计算能力。99% 的情况,都是因为我们给系统下达了矛盾的指令:一边告诉它“我有需求”,一边却通过主数据告诉它“不要计划”、“不要触发”或者“我是冻结的”。掌握这 3 个排查点,你就能在 5 分钟内解决大部分“MRP 失灵”的悬案,成为用户眼中的“系统神医”。

我小时候很黑的博客 607

最大子序列和四种解法(java)

最大子序列和解法

panrh的博客 1254

RAGFlow 系列教程 第14课:GraphRAG -- 知识图谱增强检索

RAGFlow v0.25.0深度解读了GraphRAG技术,通过构建知识图谱解决传统RAG在多跳推理问题上的局限。系统支持General GraphRAG和Light GraphRAG两种实现,包含四阶段构建流程:实体关系抽取、实体消解、社区检测和图持久化。核心代码位于rag/graphrag目录,采用LLM驱动的抽取机制,结合编辑距离和LLM确认的实体消解策略,以及Leiden社区检测算法。KGSearch模块通过多信号融合检索(实体+关系+N-hop+社区)实现高效查询。该系统将非结构化文本转化为可推

weixin_43674738的博客 102

最大子序和(Java)

求最大子序和 思想: (1)以sum为当前子序和,初始值为零;ans为当前最大子序和,初始值为num[0]。 (2)对数组进行遍历,当sum>0时,认为sum对当前正在遍历的数组元素有增益,则增加;当sum<0时,认为sum对当前正在遍历的数组元素有减损,则舍弃当前sum,以当前正在遍历的数组元素为新的sum值。 (3)在每次遍历后,将新获得的sum值与ans值相比取其最大赋值给ans...

y18771025420的博客 490

基于STM32F1XX 、HAL库的LTR-303ALS-01 环境光传感器驱动应用C语言程序设计

printf("制造商ID: 0x%02X\r\n", LTR303_ReadManufacID());printf("器件ID: 0x%02X\r\n", LTR303_ReadPartID());LTR-303ALS-01是一款数字环境光传感器(ALS),由Lite-On公司生产。printf("LTR-303ALS初始化失败!printf("LTR-303ALS初始化成功!printf("数据无效\r\n");* @param mode: 0-待机, 1-激活。

PP_Cottage的博客 1034

某城商银行生产容器云平台详细设计方案分享及经验总结

AS3模式的CIS容器部署在K8S集群内,作为F5的控制器,CIS容器通过对K8S集群内Configmap资源进行监控,将Configmap资源中的内容转化为F5的配置,将配置推送给 F5 ,CIS容器还通过K8S标准的API接口完成业务发现和实时监听集群内Pod的变化,一旦Pod发生变化,相应的更新会及时推送给F5,并完成更新。容器技术发展非常迅速,现在应用大多以容器作为承载介质,前两年在容器云上承载的应用类型主要是Web类,随着容器云领域的不断发展,越来越多的应用类型将迁移至容器云,包括有状态应用。

qq_61890005的博客 863

leetcode 53.最大子序和 Java

最大自子序和题目链接描述示例代码 题目链接 https://leetcode-cn.com/problems/maximum-subarray/ 描述 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 代码 简单的动规思想,假设dp表示以第i个元素结尾的子序的最大值,那么dp[i]可以由当前元素的值以及dp[i-1]

博主是个二次元死肥宅~ 231

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

LeetCode力扣53.最大子序和 Java

动态规划: 在这一遍扫描数组当中,从左到右记录当前子序列的和tempsum,若这个和不断增加,那么最大子序列的和max也不断增加(不断更新max)。如果往前扫描中遇到负数,那么当前子序列的和将会减小,即tempsum<nums[i],将此时的tempsum抛弃,并重新赋值为nums[i]。此时tempsum 将会小于max,当然max也就不更新。 public int maxSubArray(int[] nums) { int maxsum=nums[0]; //记录最大的子序

qq_37832544的博客 274

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

leetcode-53. 最大子序和 力扣 Java版本

最近在做回溯现在又在做dp的题还是专项去做才有效果些。 给定一个整数数组 nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释:连续子数组[4,-1,2,1] 的和最大,为6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 后面在专项...

mysql表名与列名单引号‘’引发的错误 250

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

leetcode-55-最大子序和(java)

title: leetcode-55-最大子序和(java) date: 2019-09-12 17:00:49 categories: leetcode tags: leetcode 最大子序和(java) 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: ...

weixin_42479155的博客 336

力扣java 最大子序和

最大子序和 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例 1: 输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。 示例 2: 输入:nums = [1] 输出:1 示例 3: 输入:nums = [0] 输出:0 示例 4: 输入:nums = [-1] 输出:-1 示例 5: 输入:nums = [-100000] 输出:-100000 提示: 1 .

331

Java实现 LeetCode 53 最大子序和

53. 最大子序和 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 class Solution { public...

南 墙 1万+

LeetCode 53. 最大子序和 (Java)

最大子序和 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-subarray 著...

nuts_and_bolts的博客 185

LeetCode HOT 100题目解析——动态规划:最大子序和(Java详细讲解)

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

weixin_46532327的博客 490

【LeetCode】【Java】最大子序和

确定dp数组及下标含义

生命不息,代码不止 388

LeetCode53——Java之最大子序和

以后我要养成写博客的习惯,所以呢,先开始多记录吧。 题目:最大子序和 给定一个整数数组nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释:连续子数组[4,-1,2,1] 的和最大,为6。初看题需要注意的点:这个最大和是连续的子数组。附加题:复杂度要求O(n)。思...

weixin_34279061的博客 196

LeetCode 53. 最大子序和 JAVA

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-subarray 著作权归领扣网络所有。商业转载请联系官方授权

sinb妃的博客 249

Visio 从入门到精通:绘制专业流程图与系统架构图的完整指南

在软件开发和项目管理中,流程图和系统架构图是梳理逻辑、展示设计、促进团队协作的核心工具。其原理在于通过标准化的图形符号和连接关系,将复杂的业务流程或系统结构可视化,从而提升沟通效率和设计质量。掌握专业的绘图工具,不仅能规范文档输出,更能为技术方案评审、系统维护和知识传承提供坚实基础。Visio 作为微软 Office 生态中的专业绘图软件,凭借其丰富的智能图形库和强大的格式控制能力,尤其适合绘制需要高度规范化的技术图表,如 UML 图、网络拓扑图和微服务架构图。本文将以 Visio 为核心,系统讲解从环境准

weixin_33860553的博客 392
上一篇: 蓝桥杯:练习题:回文数
下一篇: 背包问题(贪心java)
ArchitectDream
博客等级 码龄9年 48粉丝 288原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值