当前位置:网站首页>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)
};
边栏推荐
- egg. JS getting started navigation: installation, use and learning
- UnsupportedOperationException异常
- Cisp-pte practice explanation
- Process of obtaining the electronic version of academic qualifications of xuexin.com
- 同一局域网的手机和电脑相互访问,IIS设置
- @Jsonbackreference and @jsonmanagedreference (solve infinite recursion caused by bidirectional references in objects)
- 704 二分查找
- Roguelike game into crack the hardest hit areas, how to break the bureau?
- China vanadium battery Market Research and future prospects report (2022 Edition)
- Indentation of tabs and spaces when writing programs for sublime text
猜你喜欢

Light of domestic games destroyed by cracking

pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof

游戏解包的危害及资源加密的重要性

Mobile phones and computers on the same LAN access each other, IIS settings

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

C語言雙指針——經典題型

FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战

Marathon envs project environment configuration (strengthen learning and imitate reference actions)

View computer devices in LAN

JS inheritance method
随机推荐
FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
Process of obtaining the electronic version of academic qualifications of xuexin.com
Deep analysis of C language data storage in memory
Cisp-pte practice explanation
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
visdom可视化实现与检查介绍
Revit 二次开发 HOF 方式调用transaction
Image,cv2读取图片的numpy数组的转换和尺寸resize变化
Trying to use is on a network resource that is unavailable
LeetCode:剑指 Offer 42. 连续子数组的最大和
Image, CV2 read the conversion and size resize change of numpy array of pictures
软件卸载时遇到trying to use is on a network resource that is unavailable
生成器参数传入参数
Unsupported operation exception
MySQL learning record 07 index (simple understanding)
JS inheritance method
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
Beijing invitation media
egg. JS project deployment online server