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
原题链接
dp[i]:表示以 nums[i] 为结尾的连续子数组最大和。
连续子数组则必须包含 nums[i],否则不符合题意。
当 dp[i - 1] > 0 时,dp[i] = dp[i - 1] + nums[i],当 dp[i - 1] <= 0 时,dp[i] = nums[i]。
dp[i - 1] > 0
dp[i] = dp[i - 1] + nums[i]
dp[i - 1] <= 0
dp[i] = nums[i]
所以状态转移方程为:
dp[i] = max(dp[i - 1] + nums[i], nums[i])
dp[0] = nums[0],以 nums[0] 为结尾的连续子数组最大和为 nums[0]。
dp[0] = nums[0]
我们只需要关注前一个状态的值,不需要额外开辟一个数组空间记录,仅用两个变量即可。
const maxSubArray = function(nums) { const len = nums.length let res = nums[0] for (let i = 1; i < len; i++) { nums[i] = Math.max(0, nums[i - 1]) + nums[i] if (nums[i] > res) { res = nums[i] } } return res }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接
状态定义
dp[i]:表示以 nums[i] 为结尾的连续子数组最大和。
状态转移方程
连续子数组则必须包含 nums[i],否则不符合题意。
当
dp[i - 1] > 0
时,dp[i] = dp[i - 1] + nums[i]
,当dp[i - 1] <= 0
时,dp[i] = nums[i]
。所以状态转移方程为:
dp[i] = max(dp[i - 1] + nums[i], nums[i])
初始化
dp[0] = nums[0]
,以 nums[0] 为结尾的连续子数组最大和为 nums[0]。我们只需要关注前一个状态的值,不需要额外开辟一个数组空间记录,仅用两个变量即可。
The text was updated successfully, but these errors were encountered: