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:
Send email with JavaMail
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Spring Boot - Interceptor
LinkedHashSet trong java
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Use Dynamic Programming to Solve Approximate String Matching
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Spring Boot - Securing Web Applications
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Cubic convergence 1/pi Algorithm
A Guide to BitSet in Java
How to Read HTTP Headers in Spring REST Controllers
New Stream Collectors in Java 9
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Implement LinkedBlockingQueue API
Lớp HashMap trong Java
Array to String Conversions
Java Program to Perform String Matching Using String Library
Java Program to Permute All Letters of an Input String
ETags for REST with Spring
Tìm hiểu về Web Service
Java – String to Reader
Java TreeMap vs HashMap
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
XML Serialization and Deserialization with Jackson
Java Program to Implement Bloom Filter
Java Program to Implement Adjacency Matrix
Java Program to Find the Vertex Connectivity of a Graph
Guide to Spring @Autowired
ArrayList trong java