题目描述:
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
解析:
1.可以理解为寻找连续子数组,使数组加和最大。
2.新创建一个数组,每次去比较nums数组中当前的值(nums[i])和当前的值加上nums[i-1]的大小,
然后去判断是否需要开新的数组,每次比较把较大值存入变量max中
3.如果当前较大值大于max,则更新max,否则不更新,最后返回max
Java:
public int maxSubArray(int[] nums) { int[] memo = new int[nums.length]; memo[0] = nums[0]; int max = nums[0]; for(int i = 1; i < nums.length; i++) { memo[i] = Math.max(nums[i] + memo[i-1], nums[i]); max = Math.max(max, memo[i]); } return max; }
JavaScript:
var maxSubArray = function(nums) { const memo = []; memo[0] = nums[0]; let max = nums[0]; for(let i = 1; i < nums.length; i++) { memo[i] = Math.max(nums[i] + memo[i-1], nums[i]); max = Math.max(max, memo[i]); } return max; };