##53. Maximum Subarray
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.
解题思路: <br/ > Kadane's Algorithm <br/ > https://www.youtube.com/watch?v=epTQfFlhQBo <br/ > local_max: 存从开头到i的sum. 如果i之前的数为负数,到i的最大数为i. <br/ > max: 存最后的返回值,就算local_max保证了最大值,如果最大local_max之后的i位值为负,则不录入max. <br/ > 每轮比较max 和local_max的大小,大的存入max. <br/ > 最终返回 max <br/ >
public int maxSubArray(int [] nums){
int max = Integer.MIN_VALUE;
int local_max = 0;
for (int i=0; i < nums.length; i++){
local_max += nums[i];
local_max = Math.max(local_max, nums[i]);
max = Math.max(max, local_max);
}
return max;
}