53. Maximum Subarray(js)
53. Maximum Subarray
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
题意:从给定数组中提取项连续的子数组,比较所有的子数组的所有项相加之和最大,并返回这个最大值
代码如下:
/** * @param {number[]} nums * @return {number} */ //对数组进行分组,组内项相加小于零为一组,在组内找最大值和其他组进行比较 var maxSubArray = function(nums) { var sum=0; var len=nums.length; var max=nums[0]; for(var i=0;i<len;i++){ sum+=nums[i]; //组内相加大于当前最大值 max=max<sum?sum:max; //组内所有项相加小于0,继续分组 sum=sum<0?0:sum; } return max; };