LeetCode Maximum Subarray Maximum Product Subarray DP问题

如何找到区间数组的最大和?最大积? 给定一个整数数组,需要找一个子数组,使得该子数组的和是所有的子数组里边最大的,或者该子数组相乘的积是所有的子数组中最大的。 先看前者,求和具有最优子结构,也就是说前n个元素的最大和子区间和前n+1个元素的最大和子区间是有关系的,如果我们用dp[k]记录前n个数组元素中的最大和,并且规定这个子区间的最后一个元素必须是n,那么当我们计算的数组长度扩展为k+1的时候就需要考量dp[k]了,如果 阅读详情

Maximum Subarray

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

思想:

            这是个典型的动态规划的问题,求的子序列的最大值。在每一步,我们可以维护两个变量。局部最优(必须包含当前元素的最优的解):用DP[N]数组 表示以下标N结尾元素的最大值。全局最大值(就是到当前元素为止的最优解):用一个gloabl表示 找到DP[N]数组中的最大值。

DP[I] = Max(DP[I-1]+nums[i],nums[i]);//DP的动态转移方程 每遍历一遍DP[I]可以判断gloabl的最大值

可以看到DP[i]的转移是与DP[I-1]前一个元素有关 那么DP可以使用滚动数组进行优化 用一个遍历Max_local表示即可

时间O(N) 空间O(1)

AC代码:

class Solution {
public:
    int max(int a,int b){return a>b?a:b;};
    int min(int a,int b){return a<b?a:b;};
    int maxSubArray(vector<int>& nums) {
        int len =nums.size();
        if(len<=0) return 0;
        int global = nums[0];
        int max_local = nums[0];
        for(int i=1;i<len;i++){
            max_local = max(max_local+nums[i],nums[i]);
            if(global<max_local) global = max_local;
        }
        return global;
    }
};

Maximum Product Subarray

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6

思想:

这个问题和上面一题类似,也是用动态规划求解,不同的是这题是求子序列乘法的最大值。不像上一题累加结果只要是正的一定是递增,而乘法中可能现在看起来是负的,而后面跟个负数相乘就会得到最大的乘积。其实只需要3定义3个变量,一个局部最小值,一个局部最大值,一个全局最大值就能线性的时间完成最大值的求解

时间O(N) 空间O(1)

代码:

class Solution {
public:
    int max(int a,int b){return a>b?a:b;};
    int min(int a,int b){return a<b?a:b;};
    int maxProduct(vector<int>& nums) {
        int len = nums.size();
        if(len<=0) return -1;
        int max_local = nums[0];//局部最大值,以最后一个元素结尾
        int min_local = nums[0];//局部最小值,以最后一个元素结尾
        int gloabl = nums[0];//全局最大值
        for(int i=1;i<len;i++){
            //cout<<max_local<<" "<<min_local<<endl;
            int premax = max_local;
            max_local = max(max(max_local*nums[i],nums[i]),min_local*nums[i]);
            min_local = min(min(min_local*nums[i],nums[i]),premax*nums[i]);
            if(max_local>gloabl) gloabl = max_local;
        }
        return gloabl;
    }
};



Python 爬虫实战:在房天下抓取房产信息,分析房价走势 通过本次 Python 爬虫实战,我们成功地从房天下爬取了房产信息,并进行了存储、处理、分析和可视化展示。在这个过程中,我们不仅掌握了爬虫技术的基本应用,还学会了如何对动态加载的数据进行处理和分析。然而,本次爬虫任务也存在一些局限性,例如仅爬取了部分区域的房产数据,且未对房产的图片和视频内容进行分析。在未来的工作中,我们可以进一步优化爬虫程序,爬取更多区域的房产数据,并深入分析房产的多媒体内容、用户行为模式等,为购房者和房地产从业者提供更有价值的数据支持。 阅读详情

相关推荐

Xcelium XRUN实用指南:从入门到高效仿真

本文是Xcelium XRUN仿真工具的实用指南,从基础入门到高效应用全面解析。XRUN作为Cadence Xcelium的统一命令行入口,能自动化编译、精细和仿真流程,大幅提升数字芯片与FPGA验证效率。文章详细介绍了最简命令、波形调试、增量编译、多核并行仿真等核心功能,并提供了管理复杂项目、性能调优与深度调试的进阶技巧,帮助工程师快速上手并精通这一高效仿真工具。

weixin_29238147的博客 741

DP-求子数列最大和/积-MaxEndHere

@“全是套路”-leetcode总结 DP-求子数列最大和/积-MaxEndHere 这是我写的第一篇leetcode的数据结构算法练习的总结。各个论坛上有很多总结leetcode的解法的博客,但很多是按照作者的理解分类的。这里我按照我自己的思路总结,通过写可以梳理一遍,让自己思路更清晰。 有些题,表面看上去不一样,仔细想想,就会觉得,“脱了马甲我还认得你!” 今天是DP动态规划问题的一个子类,就是在某个点,若之前的累积结果已经不能再产生积极的contribution的情况下,要把之前的舍弃。 53和121

sinat_21555157的博客 304

S4HANA Rebate Management(条件合同) -Single Step

S4HANA 条件合同管理(Condition Contract Management), 包括如何创建条件合同,场景应用

m0_50200150的博客 2308

LeetCode 152. Maximum Product Subarray(动态规划)

题目来源:https://leetcode.com/problems/maximum-product-subarray/ 问题描述 152.Maximum Product Subarray Medium Given an integer arraynums, find the contiguous subarray within an array (containing at leas...

da_kao_la的博客 308

(SCADA)监控与数据采集系统

SCADA应用于监控和采集数据来控制工业过程软件。它通过收集和传输实时数据,帮助操作员监视和控制各种设备和过程。

软件技术的专栏 4545

STM32实战:如何快速移植野火PID调试助手协议到你的电机控制项目

本文详细解析了如何将野火PID调试助手协议快速移植到STM32电机控制项目中。通过深度剖析协议帧格式、数据解析逻辑及环形缓冲区应用,提供了从工程结构规划、核心函数适配到串口中断集成的完整移植步骤。文章还分享了协议健壮性增强、数据上报频率优化等高级调试技巧,帮助开发者构建稳定可靠的上位机调试通道,大幅提升PID参数整定效率。

weixin_29171129的博客 468

leetcode Maximum Product Subarray

之前好像做过这样的,以前是加法,现在是乘法。 一开始我也傻逼得用n方的试了下,肯定是TLE的。 那显然就是可以O(n)解决了 用两个dp数组,一个存最大值,一个存最小值,因为可能是负数再乘以负数就很大了,所以每次更新需要借助最小值一同更新最大值。最后遍历一边dp大的数组就有答案了。 class Solution { public: int maxProduct(i...

183

城市仿真软件:AnyLogic_(8).行人与人群动态仿真

定义行人个体的行为和属性,如行走速度、目标位置等。// 创建一个行人// 设置行走速度为1.5 m/s// 设置目标位置为入口// 创建另一个行人// 设置行走速度为1.2 m/s// 设置目标位置为出口// 创建行人// 创建乘客行人与人群动态仿真在城市规划、交通管理和紧急疏散等领域具有广泛的应用。通过AnyLogic提供的行人模型模块,可以有效地模拟行人的个体行为、群体动态和与环境的交互。

kkchenjj的博客 1250

LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **

题目:Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguo

小村长技术blog 2121

DA14531之搭建开发环境

DA14531之搭建开发环境

hejinwu1314的博客 1779

XLSX Workbench 在 ABAP 世界的定位与实战:从概念到完整示例

XLSX Workbench 在可视化、易维护与批量后台生成三方面填补了 ABAP 报表到 Excel 的空白。它与官方类及社区明星 abap2xlsx 形成了“模板驱动、代码驱动、二者兼顾”的互补格局。掌握 Workbench 后,开发者能把精力集中在业务逻辑以及数据质量,而把排版细节交给图形化工具,大幅加速交付与迭代。通过本文提供的示例,你可以立即在项目中落地并尝到效率提升的红利。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 524

[leetcode]动态规划之Maximum Product Subarray

动态规划之Maximum Product Subarray题目思考类型归类代码 题目 leetcode入口 思考 特殊在于,数组元素可能是0或者是负数。 当遇到负数的时候,最大值和最小值间会出现翻转, 即:最大值会变成最小值,最小值会变成最大值 维护两个数组 dpmin[i]:存储以元素[i]为结尾的连续一段的最大值 dpmax[i]:存储以元素[i]为结尾的连续一段的最小值 每次遍历都要 res...

crabstew的博客 278

手把手教你学 GPU SoC 芯片(9.3)--GPU SOC 功耗和热管理的动态电压和频率调整(DVFS)

通过动态电压和频率调整(DVFS),可以有效地管理GPU SoC的功耗和热管理。合理的DVFS策略不仅可以节省功耗,提高能效,还可以延长设备的使用寿命。

MHD0815的博客 1500

LeetCode Maximum Product Subarray

题意:给定一个int,求解字串的最大product 解法:dp咯 因为只是一个求解字串的product,只要考虑正负和零,当前的max[i]只和三个有关系,A[i],A[i]*max[i-1]以及A[i]*min[i-1],那么这样我们不妨同时维护两个dp数组,max和min,分别表示以A[i]结尾的字串中最大值和最小值。状态转移方程如下 max[i] = max( A[i], A[i]*m

miss_snow_m的专栏 351

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

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

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

Leetcode 152 Maximum Product Subarray

Leetcode 152 Maximum Product Subarray题目思路递推式代码优化 题目 Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1 Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the

weixin_43796689的博客 245

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

152. Maximum Product Subarray

152. Maximum Product Subarray

hello world 241

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

leetcode 53. Maximum Subarray 、152. Maximum Product Subarray

53. Maximum Subarray 之前的值小于0就不加了。dp[i]表示以i结尾当前的最大和,所以需要用一个变量保存最大值。 动态规划的方法: class Solution { public: int maxSubArray(vector<int>& nums) { vector<int> dp(nums.size(...

weixin_30707875的博客 130

Leetcode 152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest

xingyun121x的专栏 286

【leetcode每日刷题】152. Maximum Product Subarray

https://leetcode.com/problems/maximum-product-subarray/ 最大乘积子数组 # 解法一,使用两个动态数组 def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ res = nu...

菜菜鸟的博客 258

leetcode题解:第152题Maximum Product Subarray

题目 Maximum Product Subarray Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Ou...

chenf1999的博客 220

Leetcode152. Maximum Product Subarray

找一个连续的子数组,使得连乘起来最大。

magic_jiayu的博客 204

leetcode152. Maximum Product Subarray

题目:题目链接 题意:从一个数组中找到连续的子数组,其所有元素的积最大用MPS表示。 思路:dp。 先看数据量,2*10^4 所以O(n^2)肯定不行。那就是一维dp了。开始我想着设dp[i]为从0到i的MPS,但状态转移方程一直写不出来。看了看提示,设dp[i]为以i结尾的MPS。那么就很好根据前面推出后一个了。要注意因为是积,所以哪怕前面是负数也有可能再与一个负数相乘为正。所以要保存最大和最小值。 具体如下: 设max_product[i]为以i结尾的最大连续子数组积,min_product[i]为以

欲买桂花同载酒 235

[leetcode] 152. Maximum Product Subarray

Description Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation...

Learning from the mistakes 193

10.3.1 (python) 动态规划数组类LeetCode题目 —— Minimum Path Sum & Triangle & Maximum Product Subarray

这一节的几篇,都是解析动态规划数组类题目,相对于后面的字符串类问题来说,还是比较容易的。 首先来看比较几个简单的DP题目,巩固一下前面所学套路。 64.Minimum Path Sum Given amxngrid filled with non-negative numbers, find a path from top left to bottom right whichmi...

xutiantian1412的博客 424

[LeetCode] Maximum Product Subarray

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。 引用自 https://blog.youkuaiyun.com/whuwangyi/article/details/39577455 使用DP,由于负数的存在,需要同时保存当前最大值和当前最小值,所以需要维护两个DP表,...

by_qmr的博客 187

152 - Maximum Product Subarray

152 - Maximum Product Subarray

uso的博客 149
上一篇: LeetCode:Subsets I II
下一篇: LeetCode:Majority Element I II 投票算法
Mike_CSU
博客等级 码龄10年 6粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值