当前位置:网站首页>LeetCode:劍指 Offer 42. 連續子數組的最大和
LeetCode:劍指 Offer 42. 連續子數組的最大和
2022-07-06 08:45: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协议
- sys. argv
- 目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台
- Colorlog combined with logging to print colored logs
- Golang force buckle leetcode 1020 Number of enclaves
- LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
- Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
- PC easy to use essential software (used)
- 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
猜你喜欢
Promise 在uniapp的简单使用
704 binary search
swagger设置字段required必填
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
软件卸载时遇到trying to use is on a network resource that is unavailable
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
Visual implementation and inspection of visdom
Navicat premium create MySQL create stored procedure
FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
TP-LINK 企业路由器 PPTP 配置
随机推荐
Unsupported operation exception
Is it safe to open an account in Zheshang futures?
Colorlog combined with logging to print colored logs
swagger设置字段required必填
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
[NVIDIA development board] FAQ (updated from time to time)
R language uses the principal function of psych package to perform principal component analysis on the specified data set. PCA performs data dimensionality reduction (input as correlation matrix), cus
【ROS】usb_ Cam camera calibration
PC easy to use essential software (used)
有效提高软件产品质量,就找第三方软件测评机构
torch建立的网络模型使用torchviz显示
The problem and possible causes of the robot's instantaneous return to the origin of the world coordinate during rviz simulation
Revit 二次开发 HOF 方式调用transaction
Esp8266-rtos IOT development
JS inheritance method
@JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
[embedded] cortex m4f DSP Library
[MySQL] log
【嵌入式】Cortex M4F DSP库