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
.
解析
常见的解决方法是计算每个子数组并比较大小,时间复杂度为O(n^2)。
本文使用一种时间复杂度为O(n)的方法解决:
步骤:从数组第一个元素开始遍历并做累加,若累加值小于0则抛弃,重新累加。
public class Solution {
public int maxSubArray(int[] nums) {
int res = -2147483647;
int temp = 0;
for(int n : nums){
if(temp < 0) temp = 0;
temp += n;
if(res < temp) res = temp;
}
return res;
}
}