leetcode:https://leetcode.com/problems/maximum-subarray/#/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
.
package go.jacob.day622;
/**
* [leetcode]53. Maximum Subarray
* @author Administrator
*
*/
public class Demo2 {
/*
* 202 / 202 test cases passed.
* Status: Accepted
* Runtime: 16 ms
* tc:O(n)
*/
public int maxSubArray(int[] nums) {
if (nums == null || nums.length < 1)
return -1;
int sum = 0, maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum > maxSum)
maxSum = sum;
if (sum <= 0)
sum = 0;
}
return maxSum;
}
}