当前位置:网站首页>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)
};
边栏推荐
- 目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台
- 2022.02.13 - NC003. Design LRU cache structure
- 可变长参数
- @JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
- FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
- 企微服务商平台收费接口对接教程
- 2022.02.13 - NC002. sort
- Current situation and trend of character animation
- Image,cv2读取图片的numpy数组的转换和尺寸resize变化
- 【Nvidia开发板】常见问题集 (不定时更新)
猜你喜欢

电脑清理,删除的系统文件

What is CSRF (Cross Site Request Forgery)?

Generator parameters incoming parameters

2022.02.13 - NC001. Reverse linked list

vb.net 随窗口改变,缩放控件大小以及保持相对位置

Bottom up - physical layer

企微服务商平台收费接口对接教程
![Verrouillage [MySQL]](/img/ce/9f8089da60d9b3a3f92a5e4eebfc13.png)
Verrouillage [MySQL]

Sort according to a number in a string in a column of CSV file

Charging interface docking tutorial of enterprise and micro service provider platform
随机推荐
Leetcode question brushing (5.28) hash table
[cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
pytorch训练好的模型在加载和保存过程中的问题
【MySQL】日志
Trying to use is on a network resource that is unavailable
@Jsonbackreference and @jsonmanagedreference (solve infinite recursion caused by bidirectional references in objects)
Roguelike game into crack the hardest hit areas, how to break the bureau?
MySQL learning record 10getting started with JDBC
个人电脑好用必备软件(使用过)
【MySQL】锁
The mysqlbinlog command uses
2022.02.13 - NC001. Reverse linked list
Delay initialization and sealing classes
Bitwise logical operator
可变长参数
Shift Operators
Unified ordering background interface product description Chinese garbled
Sublime text using ctrl+b to run another program without closing other runs
企微服务商平台收费接口对接教程
C語言雙指針——經典題型