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.
/*
* Java Program to Find the maximum subarray sum O(n^2)time
* (naive method)
*/
import java.util.Scanner;
public class MaxSubarraySum1
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of elements in array");
int N = scan.nextInt();
int[] arr = new int[ N ];
/* Accept N elements */
System.out.println("Enter "+ N +" elements");
for (int i = 0; i < N; i++)
arr[i] = scan.nextInt();
System.out.println("Max sub array sum = "+ max_sum(arr));
}
public static int max_sum(int[] arr)
{
int N = arr.length, max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++)
{
int sum = 0;
for (int j = i; j < N; j++)
{
sum += arr[j];
if (sum > max)
max = sum;
}
}
return max;
}
}
Enter number of elements in array 8 Enter 8 elements -2 -5 6 -2 -3 1 5 -6 Max sub array sum = 7
Related posts:
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Construct an Expression Tree for an Infix Expression
Java Program to implement Priority Queue
Java String to InputStream
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
The Registration Process With Spring Security
Connect through a Proxy
Dynamic Proxies in Java
Uploading MultipartFile with Spring RestTemplate
Serialize Only Fields that meet a Custom Criteria with Jackson
JWT – Token-based Authentication trong Jersey 2.x
Phân biệt JVM, JRE, JDK
An Introduction to ThreadLocal in Java
Using Spring @ResponseStatus to Set HTTP Status Code
Introduction to Spring MVC HandlerInterceptor
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Reversing a Linked List in Java
Guide to CopyOnWriteArrayList
Java Program to Implement Find all Back Edges in a Graph
An Introduction to Java.util.Hashtable Class
Spring 5 Testing with @EnabledIf Annotation
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Multipart Upload with HttpClient 4
Send email with JavaMail
Xử lý ngoại lệ trong Java (Exception Handling)
A Quick Guide to Using Keycloak with Spring Boot
Java Program to Implement Pairing Heap
Intersection of Two Lists in Java
Java Program to Perform Stooge Sort
Introduction to Using Thymeleaf in Spring
Java Program to Implement Range Tree
Java Program to Implement Hash Tables with Linear Probing