Given an array of integers, find a contiguous subarray which has the largest sum.
Notice
The subarray should contain at least one number.
Have you met this question in a real interview?
Yes
Example
Given the array[−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray[4,−1,2,1]has the largest sum =6.
当遇到一个新元素时,有两个选择,包括进答案,或者从新开始统计答案
所以当之前的元素和为负时,就从新统计答案 如果不为负就继续统计答案
public class Solution {
/*
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (sum < 0) {
sum = 0;
}
sum += nums[i];
max = Math.max(max, sum);
}
return max;
}
}