当前位置:网站首页>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)
};
边栏推荐
- 软件压力测试常见流程有哪些?专业出具软件测试报告公司分享
- Report on Market Research and investment prospects of China's silver powder industry (2022 Edition)
- Simple use of promise in uniapp
- egg. JS getting started navigation: installation, use and learning
- egg. JS project deployment online server
- egg. JS directory structure
- C语言深度解剖——C语言关键字
- Leetcode skimming (5.29) hash table
- Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
- 电脑清理,删除的系统文件
猜你喜欢
延迟初始化和密封类
TP-LINK enterprise router PPTP configuration
JVM quick start
C語言雙指針——經典題型
TCP/IP协议
软件卸载时遇到trying to use is on a network resource that is unavailable
win10系统中的截图,win+prtSc保存位置
Synchronized solves problems caused by sharing
2022.02.13 - NC003. Design LRU cache structure
PLT in Matplotlib tight_ layout()
随机推荐
win10系统中的截图,win+prtSc保存位置
poi追加写EXCEL文件
[NVIDIA development board] FAQ (updated from time to time)
Visual implementation and inspection of visdom
PLT in Matplotlib tight_ layout()
MySQL learning records 12jdbc operation transactions
JS inheritance method
Tcp/ip protocol
ROS编译 调用第三方动态库(xxx.so)
Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
visdom可视化实现与检查介绍
Simple use of promise in uniapp
China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
自动化测试框架有什么作用?上海专业第三方软件测试公司安利
【ROS】usb_cam相机标定
PC easy to use essential software (used)
sublime text中conda环境中plt.show无法弹出显示图片的问题
C語言雙指針——經典題型
移位运算符