当前位置:网站首页>LeetCode:剑指 Offer 42. 连续子数组的最大和
LeetCode:剑指 Offer 42. 连续子数组的最大和
2022-07-06 08:44:00 【Bertil】
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为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
注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/
解题思路
1.首先定义dp数组表示以当前元素做结尾的最大子序列和,然后遍历nums数组求每个dp元素值,最后返回最大值即可
2.状态转移方程:dp[i] = Math.max(nums[i], dp[i - 1] + nums[i])
代码
/** * @param {number[]} nums * @return {number} */
var maxSubArray = function(nums) {
let dp = [nums[0]]
for(let i = 1; i < nums.length; i ++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i])
}
return Math.max(...dp)
};
边栏推荐
- Generator parameters incoming parameters
- POI add write excel file
- Leetcode question brushing (5.31) string
- The mysqlbinlog command uses
- [cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
- Crash problem of Chrome browser
- ESP8266-RTOS物联网开发
- Is it safe to open an account in Zheshang futures?
- 电脑F1-F12用途
- Bitwise logical operator
猜你喜欢
2022.02.13 - NC002. sort
Navicat premium create MySQL create stored procedure
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
软件卸载时遇到trying to use is on a network resource that is unavailable
PC easy to use essential software (used)
MySQL learning record 10getting started with JDBC
Process of obtaining the electronic version of academic qualifications of xuexin.com
Indentation of tabs and spaces when writing programs for sublime text
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
[brush questions] top101 must be brushed in the interview of niuke.com
随机推荐
深度剖析C语言指针
Leetcode skimming (5.29) hash table
MySQL learning record 10getting started with JDBC
egg. JS project deployment online server
Function coritization
Navicat Premium 创建MySql 创建存储过程
egg. JS getting started navigation: installation, use and learning
China Light conveyor belt in-depth research and investment strategy report (2022 Edition)
Precise query of tree tree
Modify the video name from the name mapping relationship in the table
UnsupportedOperationException异常
电脑F1-F12用途
如何进行接口测试测?有哪些注意事项?保姆级解读
Charging interface docking tutorial of enterprise and micro service provider platform
On the inverse order problem of 01 knapsack problem in one-dimensional state
Synchronized solves problems caused by sharing
Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
Beijing invitation media
TP-LINK 企业路由器 PPTP 配置
广州推进儿童友好城市建设,将探索学校周边200米设安全区域