Java Program to Find the Maximum Subarray Sum using 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. }

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
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.