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:
File Upload with Spring MVC
Java Program to Implement Miller Rabin Primality Test Algorithm
A Guide to @RepeatedTest in Junit 5
Java Program to Check whether Graph is Biconnected
A Guide to System.exit()
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Implement Rope
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Spring Boot - Build Systems
Send an email using the SMTP protocol
A Comparison Between Spring and Spring Boot
How to use the Spring FactoryBean?
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Shuffling Collections In Java
Java Program to Implement Circular Doubly Linked List
Java Program to subtract two large numbers using Linked Lists
A Guide to ConcurrentMap
Java Timer
Spring WebClient Requests with Parameters
The Difference Between Collection.stream().forEach() and Collection.forEach()
Working with Network Interfaces in Java
Spring Boot - Cloud Configuration Client
Add Multiple Items to an Java ArrayList
Hướng dẫn sử dụng Java Annotation
Java Program to Implement Rolling Hash
Concrete Class in Java
The Basics of Java Security
Introduction to Spring Data MongoDB
Notify User of Login From New Device or Location
Java Program to Implement Bloom Filter
Guide to BufferedReader