Monday, October 5, 2015

[19.7] Find the continuous sequence with the largest sum

1. Example

Input :{2,-8,3,-2,4,-10}
Output:  the largest sum is 5 <=== {3,-2,4}


{-3,-10,-5}
A) -3
B) 0
c) Minimum_Int
==> B


2. Implementation


public int getMaxSum(int[] a)
{





     // vlaidate the input
     if ( a== null || a.length == 0)
         return Integer.MIN_VALUE;




     int local = a[0];
     int global = a[0];
     




     for (int i =1; i < a.length;i++)
     {
          local = Math.max(local+a[i],a[i]);
          global = Math.max(local, global);
     }



     

     return global;




}

 l=2, g =2, s= 2
i =1 , -8
 l = max(s-8, -8) = -6
 g = max(-6,2) = 2
i=2, 3
 l = max(-6+3, 3) = 3
 g = max(2, 3)   = 3
i=3,-2
 s = -7
 l=max(3+-2, -2) = 1
 g = max(3,-2) = 3
i=4, 4
  l = max(1+4,4) = 5
  g = max(5,3) = 5

3. Similar ones

No comments:

Post a Comment