当前位置:网站首页>leetcode 剑指 Offer 42. 连续子数组的最大和
leetcode 剑指 Offer 42. 连续子数组的最大和
2022-07-30 08:52:00 【kt1776133839】
题目描述:
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
样例:
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
解题思路:
动态规划
状态定义: 设动态规划列表 dp ,dp[i] 代表以元素 nums[i] 为结尾的连续子数组最大和。
为何定义最大和 dp[i] 中必须包含元素 nums[i]:保证 dp[i] 递推到 dp[i+1] 的正确性;如果不包含 nums[i] ,递推时则不满足题目的 连续子数组 要求。
转移方程: 若 dp[i−1]≤0 ,说明 dp[i−1] 对 dp[i] 产生负贡献,即 dp[i−1]+nums[i]还不如 nums[i]本身大。
当 dp[i−1]>0 时:执行 dp[i]=dp[i−1]+nums[i];
当 dp[i−1]≤0 时:执行 dp[i]=nums[i] ;
初始状态: dp[0]=nums[0],即以 nums[0] 结尾的连续子数组最大和为 nums[0]。
返回值: 返回 dp 列表中的最大值,代表全局最大值。

Java程序:
class Solution {
public int maxSubArray(int[] nums) {
int res = nums[0];
for(int i = 1; i < nums.length; i++) {
nums[i] += Math.max(nums[i - 1], 0);
res = Math.max(res, nums[i]);
}
return res;
}
}
边栏推荐
猜你喜欢

Access to display the data

2022 Hangzhou Electric Multi-School 2nd Game

Integral Topic Notes - Path Independent Conditions

Field interpretation under "Surgical variables (RX SUMM-SURG OTH REG/DIS)" in SEER database

MySQL【运算符】

The FPGA based protocol 2: the I2C read and write E squared PROM

STM8L_库函数-模板搭建

开关电源波纹的产生、测量及抑制,一篇全搞定!

How to Assemble a Registry

leetcode-990:等式方程的可满足性
随机推荐
Network/Information Security Top Journal and Related Journals Conference
Leetcode - 990: equations of satisfiability
Use the R language to read the csv file into a data frame, and then view the properties of each column.
C# 之 $ – 字符串内插
七大排序之直接选择排序
浅论各种调试接口(JTAG、SWD、RDI、Jlink、Ulink、STlink)的区别
Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】
公共Jar包的版本管理
[Fun BLDC series with zero basics] Taking GD32F30x as an example, the timer related functions are explained in detail
利用R语言读取csv文件入一个数据框,然后查看各列的属性。
2022 Hangzhou Electric Multi-School 1st Game
PyQt5快速开发与实战 8.1 窗口风格
日志导致线程Block的这些坑,你不得不防
The FPGA based protocol 2: the I2C read and write E squared PROM
The difference between DDR, GDDR, QDR
宝塔搭建DM企业建站系统源码实测
微软 SQL 服务器被黑,带宽遭到破坏
功能测试、UI自动化测试(web自动化测试)、接口自动化测试
积分简明笔记-第一类曲线积分的类型
How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?