当前位置:网站首页>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)
};
边栏推荐
- Tcp/ip protocol
- visdom可视化实现与检查介绍
- MySQL learning record 07 index (simple understanding)
- 704 二分查找
- Indentation of tabs and spaces when writing programs for sublime text
- 【MySQL】锁
- 【Nvidia开发板】常见问题集 (不定时更新)
- JS pure function
- Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因
- China polyether amine Market Forecast and investment strategy report (2022 Edition)
猜你喜欢

Problems in loading and saving pytorch trained models

JS inheritance method

JVM 快速入门

Tcp/ip protocol

UnsupportedOperationException异常

堆排序详解

ROS compilation calls the third-party dynamic library (xxx.so)

Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform

Image, CV2 read the conversion and size resize change of numpy array of pictures
![[embedded] print log using JLINK RTT](/img/22/c37f6e0f3fb76bab48a9a5a3bb3fe5.png)
[embedded] print log using JLINK RTT
随机推荐
按位逻辑运算符
Function coritization
JS pure function
R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
Cisp-pte practice explanation
TCP/IP协议
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 camera calibration
On the inverse order problem of 01 knapsack problem in one-dimensional state
Indentation of tabs and spaces when writing programs for sublime text
The mysqlbinlog command uses
Golang force buckle leetcode 1020 Number of enclaves
visdom可视化实现与检查介绍
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
The network model established by torch is displayed by torch viz
延迟初始化和密封类
C语言双指针——经典题型
Revit 二次开发 HOF 方式调用transaction
[embedded] cortex m4f DSP Library
sublime text中conda环境中plt.show无法弹出显示图片的问题