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:
Introduction to the Java NIO2 File API
Function trong Java 8
Java Program to Permute All Letters of an Input String
Spring Boot - Enabling Swagger2
Lập trình đa luồng với CompletableFuture trong Java 8
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Implement Sorted List
So sánh Array và ArrayList trong Java
Guide to the Volatile Keyword in Java
A Quick Guide to Spring Cloud Consul
A Guide to Iterator in Java
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Jackson – Marshall String to JsonNode
Map Interface trong java
Java TreeMap vs HashMap
HttpClient Basic Authentication
Java Program to Implement Floyd Cycle Algorithm
Hướng dẫn Java Design Pattern – Builder
Java – Write an InputStream to a File
Summing Numbers with Java Streams
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Describe the Representation of Graph using Adjacency Matrix
Jackson – Unmarshall to Collection/Array
Hướng dẫn Java Design Pattern – Singleton
ClassNotFoundException vs NoClassDefFoundError
Spring Boot - Enabling HTTPS
Testing in Spring Boot
Mapping a Dynamic JSON Object with Jackson
Java Program to Implement Threaded Binary Tree
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement Stack using Linked List