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:
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Spring Boot - Runners
Debugging Reactive Streams in Java
Java Program to Implement Leftist Heap
Java Program to Implement Insertion Sort
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java Program to Find kth Largest Element in a Sequence
Chuyển đổi Array sang ArrayList và ngược lại
How to Break from Java Stream forEach
Create a Custom Exception in Java
Java Program to find the peak element of an array using Binary Search approach
Why String is Immutable in Java?
Guide to Spring @Autowired
Java Program to Implement Pollard Rho Algorithm
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Introduction to PCollections
Redirect to Different Pages after Login with Spring Security
Java Program to Implement Merge Sort Algorithm on Linked List
Spring JDBC
A Guide to WatchService in Java NIO2
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Java Program to Implement Fibonacci Heap
Spring MVC Custom Validation
Java Program to Find a Good Feedback Vertex Set
Immutable Map Implementations in Java
Java Program to Implement Lloyd’s Algorithm
Simple Single Sign-On with Spring Security OAuth2
Java Program to Implement Repeated Squaring Algorithm
Java – Reader to Byte Array
Introduction to Spliterator in Java
Join and Split Arrays and Collections in Java
Java Program to Implement a Binary Search Tree using Linked Lists