Maximum Subarray (JAVA)

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

 

 1  public static int maxSubArray(int[] A) 

 2      {

 3             int max=A[0];

 4             for(int i=0;i<A.length;i++)

 5             {

 6                 int sum=0;

 7                 for(int j=i;j<A.length;j++)

 8                 {

 9                     sum+=A[j];

10                     if(sum>max)12                         max=sum;15                 }

16             }

17                 

18          return max;

19       }

 

 

O(n):

 public static int maxSubArray(int[] A) 

     {

         int max=A[0];

         int sum=0;

         for(int i=0;i<A.length;i++)

         {

             sum+=A[i];

             if(sum>max)

                 max=sum;

             

             if(sum<0)

             sum=0;

         }

         return max;

     }

 

你可能感兴趣的:(array)