Max Sum Contiguous Subarray

Max Sum Contiguous Subarray

 
Find the largest sum of a given contiguous subarray
 
int[] array = { -2, 1, -3, 3, -1, 2, 1, -5, 4 };
 
Output:  5
 
Here is the code.
 



public class MaxSumContiguousArray {
public static void main(String[] args) {
int[] array = { -2, 1, -3, 3, -1, 2, 1, -5, 4 };
System.out.println(getMaxSum(array));
}
private static int getMaxSum(int[] array) {
int max = Integer.MIN_VALUE;
int current = 0;
for (int i = 0; i < array.length; i++) {
current += array[i];
if (current > max) {
max = current;
}
if (current < 0) {
current = 0;
}
}
return max;
}
}


 
Output:

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON