Maximum Sum of All Sub-arrays

Question: A sub-array has one number of some continuous numbers. Given an integer array with positive numbers and negative numbers, get the maximum sum of all sub-arrays. Time complexity should be O(n).
For example, in the array {1, -2, 3, 10, -4, 7, 2, -5}, its sub-array {3, 10, -4, 7, 2} has the maximum sum 18.
Solution : Analyze arrays number by number
store 1st element as the largest, add the 2nd, if sum is smaller the the current number, discard the current largest and use the current number.
class MaxSub{
 public int findMaxSub(int[] a){
 if(a== null || a.length == 0) return new ImporperInputException();
 if(a.length == 1) return a[0];
 int tempMax=a[0], startIndex=0, endIndex=0; sum=a[0];
 for(int i=1; i<a.length; i++){
 sum=a[i]+tempMax;
 if(a[i] >= tempMax){
 tempMax=a[i]
 startIndex = i;
 endIndex = i;
 sum=a[i];
} else{
 if(sum>tempMax){
 tempMax=sum; endIndex=i;}
}
}
 return tempMax;
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s