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.
这里的方法利用一个dp数组,数组里保存的是以第i个元素为结尾的最大和子数组的和,那么dp[i+1]就是dp[i] > 0 ? nums[i+1] + dp[i] :nums[i+1]
var maxSubArray = function(nums) {
var num = nums.length;
if (num===0)
return 0;
var dp = [nums[0]];
var max = nums[0];
for(var i = 0;i < nums.length;i++) {
dp[i] = dp[i-1] > 0 ? nums[i] + dp[i-1] :nums[i];
max = Math.max(dp[i],max);
}
return max;
};