We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
53. 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
nums
示例1:
输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
The text was updated successfully, but these errors were encountered:
构建 dp 数组,dp保存遍历进行到i的最大和,进入遍历,每次对比nums[i]大还是nums[i]+dp[i - 1]对dp[i]进行赋值。
i
nums[i]
nums[i]+dp[i - 1]
dp[i]
复杂度为 O(N)
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { const dp = Array(nums.length); dp[0] = nums[0]; let max = nums[0]; for (let i = 1; i < nums.length; i++) { dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]); if (max < dp[i]) { max = dp[i]; } } return max; };
Sorry, something went wrong.
No branches or pull requests
题目
给定一个整数数组
nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。示例1:
The text was updated successfully, but these errors were encountered: