Java Program to find the maximum subarray sum O(n^2) time(naive method)

«
»
This is a Java Program to find maximum subarray sum of an array. A subarray is a continuous portion of an array. The time complexity of the following program is O (n2).

Here is the source code of the Java program to find maximum subarray sum. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  * Java Program to Find the maximum subarray sum O(n^2)time 
  3.  * (naive method)
  4.  */
  5. import java.util.Scanner;
  6.  
  7. public class MaxSubarraySum1
  8. {
  9.     public static void main(String[] args) 
  10.     {
  11.         Scanner scan = new Scanner(System.in);
  12.         System.out.println("Enter number of elements in array");
  13.         int N = scan.nextInt();
  14.         int[] arr = new int[ N ];
  15.         /* Accept N elements */
  16.         System.out.println("Enter "+ N +" elements");
  17.         for (int i = 0; i < N; i++)
  18.             arr[i] = scan.nextInt();
  19.         System.out.println("Max sub array sum  = "+ max_sum(arr));
  20.     }
  21.     public static int max_sum(int[] arr)
  22.     {
  23.         int N = arr.length, max = Integer.MIN_VALUE;
  24.         for (int i = 0; i < N; i++)
  25.         {
  26.             int sum = 0;
  27.             for (int j = i; j < N; j++)
  28.             {
  29.                 sum += arr[j];
  30.                 if (sum > max)
  31.                     max = sum;
  32.             }
  33.         }
  34.         return max;    
  35.     }
  36. }

advertisement
Enter number of elements in array
8
Enter 8 elements
-2 -5 6 -2 -3 1 5 -6
Max sub array sum  = 7

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter