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 Streams vs Vavr Streams
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java – InputStream to Reader
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Java Program to Implement the Program Used in grep/egrep/fgrep
Java Program to Implement Stack API
Spring Boot - Service Components
Hướng dẫn Java Design Pattern – Proxy
Java Program to Implement Sieve Of Sundaram
Introduction to Spring Method Security
Adding a Newline Character to a String in Java
Spring Security 5 – OAuth2 Login
Implementing a Binary Tree in Java
Spring Boot - Bootstrapping
CyclicBarrier in Java
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Java Program to Implement Hash Trie
Một số ký tự đặc biệt trong Java
Java Program to Check whether Undirected Graph is Connected using DFS
Retrieve User Information in Spring Security
Java Program to Compare Binary and Sequential Search
Guide to the Java ArrayList
Using Spring @ResponseStatus to Set HTTP Status Code
Marker Interface trong Java
Java Program to Solve TSP Using Minimum Spanning Trees
The Dining Philosophers Problem in Java
Remove HTML tags from a file to extract only the TEXT
Java Program to Solve a Matching Problem for a Given Specific Case
Chuyển đổi Array sang ArrayList và ngược lại
Multi Dimensional ArrayList in Java
The Registration API becomes RESTful
HttpClient Basic Authentication