给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
您在真实的面试中是否遇到过这个题?给出数组[−2,2,−3,4,−1,2,1,−5,3]
,符合要求的子数组为[4,−1,2,1]
,其最大和为6
子数组最少包含一个数
要求时间复杂度为O(n)
相关题目 Expand
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(ArrayList<Integer> nums) {
// write your code
if(null==nums||0==nums.size()){
return 0;
}
int sum = nums.get(0);
int max = sum;
for(int i=1;i<nums.size();i++){
if(sum>0){
sum += nums.get(i);
}else{
sum = nums.get(i);
}
if(max<sum){
max = sum;
}
}
return max;
}
}