Maximum SubArray Sum – Java Source Code

Given an array of positive and negative numbers. Find the contiguous sub array of maximum sum.

   public static void subArraySum(int a[])
  {
    int i=0;
    int j=0;
    int start=0;
    int end=0;
    int maxSum = -99999;
    int cSum = 0;
    while(j < a.length)
    {
       cSum +=a[j];
       if(cSum>maxSum)// Set this as the new result
       {
          start=i;
          end = j;
          maxSum=cSum;
       }else if(cSum < 0)
       {
         cSum=0;
         i=j+1;
       }
       j++;
    }
    System.out.println("start="+start+" end="+end+" maxSum="+maxSum);

  }

Leave a Reply