Skip to content
New issue

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. 最大子序和 #11

Open
Ray-56 opened this issue Jun 4, 2020 · 1 comment
Open

✅53. 最大子序和 #11

Ray-56 opened this issue Jun 4, 2020 · 1 comment

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Jun 4, 2020

53. 最大子序和

题目

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例1:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6
@Ray-56
Copy link
Owner Author

Ray-56 commented Jun 4, 2020

构建 dp 数组,dp保存遍历进行到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;
};

@Ray-56 Ray-56 changed the title 53. 最大子序和 ✅53. 最大子序和 Jun 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant