Description:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array[-2,1,-3,4,-1,2,1,-5,4]
,the contiguous subarray[4,-1,2,1]
has the largest sum =6
.
My code:
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = nums[0];
for(let i = 0; i < nums.length; i++) {
let sum = 0;
for(let j = i; j < nums.length; j++) {
sum += nums[j];
if(max < sum) {
max = sum;
}
}
}
return max;
};
Note: 需要注意数组中只有负数的情况,不能直接赋初始max为0
网友评论