Sunday, September 16, 2018

Largest Sum contiguous subarray


 Problem . 

 An array can contains negative and positive numbers. You have to find the sub-array where the sum of all numbers in the sub array is maximum.










In the above example the largest sum in a sub-array is 14.



Solution.


The crux of the logic is the fact that, as you read from left, if a subset sums up to a -ve number, you can discard it. It won't be able to contribute anything to the numbers following it.

You need to keep track of two sums. First, the largest sum found so far from beginning (maxSoFar ) and another sum  for the sub-array currently being considered (currentSubArrayMax ). Whenever
sum of the current sub-array is more than the global max assign maxSoFar = currentSubArrayMax.


public static int maxSumSubArray (int[] numbers)
{


int currentSubArrayMax = 0;
int maxSoFar = 0;

for (int i = 0; i < numbers.length; i++)
{
currentSubArrayMax += numbers[i];



//if a subset adds up to a -ve number, discard it
if (currentSubArrayMax  < 0)
currentSubArrayMax = 0;

//set the new maximum
if (maxSoFar < currentSubArrayMax)
maxSoFar = currentSubArrayMax;
}

return maxSoFar ;
}