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:
Spring Security 5 – OAuth2 Login
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Request a Delivery / Read Receipt in Javamail
Java Program to Perform Finite State Automaton based Search
Introduction to the Java NIO2 File API
Configuring a DataSource Programmatically in Spring Boot
Guide to Spring 5 WebFlux
Setting the Java Version in Maven
Java Program to Implement Quick Sort with Given Complexity Constraint
Jackson – Marshall String to JsonNode
Java Program to Perform Naive String Matching
Java String to InputStream
Java – Write an InputStream to a File
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Spring Data Reactive Repositories with MongoDB
Date Time trong Java 8
Java – Reader to Byte Array
Spring Boot - Zuul Proxy Server and Routing
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Java Program to Optimize Wire Length in Electrical Circuit
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Spring Cloud – Tracing Services with Zipkin
Java InputStream to String
Spring Boot - Database Handling
Testing an OAuth Secured API with Spring MVC
Testing in Spring Boot
Xử lý ngoại lệ trong Java (Exception Handling)
The Registration Process With Spring Security
Lập trình mạng với java
Guide to Java Instrumentation
Java Program to Implement Sorted Doubly Linked List
Java Program to Check Whether Topological Sorting can be Performed in a Graph