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.
public int maxSubArray(int[] nums) {
int length = nums.length;
long max = nums[0];
long tmpsum = 0;
for (int i = 0; i < length; i++) {
tmpsum+=nums[i];
max = Math.max(max,tmpsum);
if (tmpsum<0){
tmpsum=0;
}
}
return (int)max;
}
很巧妙的:如果array[i...j]为最大和子串,则i<=k<=j,array[i...k]>0