The idea is to loop the array, with two variables to save current status and max result. Remember when the loop is done, update the result as well.
Commented part is easier to understand, slightly.
public class Solution {
public int maxSubArray(int[] A) {
if(A == null || A.length == 0){
return 0;
}
int curSum = A[0];
int result = A[0];
int index = 1;
while(index < A.length){
if(curSum + A[index] < curSum){
if(curSum > result){
result = curSum;
}
}
if(curSum < 0){
curSum = A[index];
}else{
curSum = curSum + A[index];
}
index++;
}
if(curSum > result){
result = curSum;
}
// int curSum = A[0];
// int result = A[0];
// int index = 1;
// while(index < A.length){
// if(curSum + A[index] >= curSum ){
// if(curSum > 0){
// curSum = curSum + A[index];
// }else{
// curSum = A[index];
// }
// }else{
// if(curSum > result){
// result = curSum;
// }
// curSum += A[index];
// if(curSum < 0){
// curSum = A[index];
// }
// }
// index++;
// }
// if(curSum > result){
// result = curSum;
// }
return result;
}
}
没有评论:
发表评论