当前位置:网站首页>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;
}
}
边栏推荐
- The FPGA based protocol 2: the I2C read and write E squared PROM
- PyQt5快速开发与实战 7.4 事件处理机制入门 and 7.5 窗口数据传递
- R安装包出现error in rawtochar(block[seq_len(ns)]) :
- Google Cloud Spanner的实践经验
- PyTorch安装及环境配置(Win10)
- Concise Notes on Integrals - Types of Curve Integrals of the First Kind
- Only after such a stage of development can digital retail have a new evolution
- 涛思 TDengine 2.6+优化参数
- 虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决
- els 方块、背景上色
猜你喜欢

【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作

剖析SGI STL空间配置器(空间配置器的重要性和重要成员及函数)

【云原生】Kubernetes入门详细讲解

ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability

Jetpack Compose 从入门到入门(八)

Concise Notes on Integrals - Types of Curve Integrals of the Second Kind

PyTorch安装及环境配置(Win10)

积分专题笔记-曲线面积分三大公式

TreeSet解析

Circuit analysis: constant current source circuit composed of op amp and triode
随机推荐
回板后,处理器不启动,怎么办?
用示波器揭示以太网传输机制
C language classic practice questions (3) - "Hanoi Tower (Hanoi)"
How to avoid CMDB becoming a data island?
342 · Valley Sequence
TreeSet parsing
积分简明笔记-第二类曲线积分的类型
九九乘法表
Is R&D moving to FAE (Field Application Engineer), is it moving away from technology?Is there a future?
如何避免CMDB沦为数据孤岛?
剖析SGI STL空间配置器(allocate内存分配函数)
一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
Farthest Point Sampling - D-FPS vs F-FPS
How to implement Golang DES encryption and decryption?
20220728使用电脑上的蓝牙和汇承科技的蓝牙模块HC-05配对蓝牙串口传输
qsort 函数的使用及其模拟实现
iperf3 参数选项详细说明
C# 之 $ – 字符串内插
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
HashSet和LinkedHashSet