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:
Bootstrap a Web Application with Spring 5
Constructor Injection in Spring with Lombok
Java 8 – Powerful Comparison with Lambdas
Java Program to Implement AVL Tree
Properties with Spring and Spring Boot
Wiring in Spring: @Autowired, @Resource and @Inject
Java Program to Perform integer Partition for a Specific Case
JWT – Token-based Authentication trong Jersey 2.x
Java Program to Implement Stack using Linked List
Map Serialization and Deserialization with Jackson
Functional Interfaces in Java 8
Java Program to Implement K Way Merge Algorithm
Hướng dẫn Java Design Pattern – Object Pool
A Guide to Iterator in Java
Java Program to Implement Find all Forward Edges in a Graph
Java Program to Implement Pagoda
Hướng dẫn Java Design Pattern – Memento
Java Program to Find the Vertex Connectivity of a Graph
Guide to System.gc()
Quick Guide to @RestClientTest in Spring Boot
Simple Single Sign-On with Spring Security OAuth2
Using a Mutex Object in Java
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
The XOR Operator in Java
Java Program to Implement Threaded Binary Tree
Java Program to Implement Tarjan Algorithm
Giới thiệu Google Guice – Injection, Scope
Hướng dẫn Java Design Pattern – Mediator
Hướng dẫn Java Design Pattern – Iterator
Spring WebClient Filters
Java Program to Implement Knapsack Algorithm
Spring MVC Content Negotiation