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:
Jackson – Bidirectional Relationships
Java Collections Interview Questions
Java Program to Implement Iterative Deepening
Configure a Spring Boot Web Application
Hướng dẫn Java Design Pattern – Prototype
Java Program to Implement Splay Tree
Java Program to Implement Adjacency List
Explain about URL and HTTPS protocol
Send email with JavaMail
Examine the internal DNS cache
Java Program to Implement Quick Sort Using Randomization
A Guide to WatchService in Java NIO2
An Introduction to ThreadLocal in Java
How to Iterate Over a Stream With Indices
Spring Security OAuth Login with WebFlux
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Program to Implement Sorted Array
Spring Boot - Tracing Micro Service Logs
Assert an Exception is Thrown in JUnit 4 and 5
Java Program to find the number of occurrences of a given number using Binary Search approach
Send email with authentication
The Java 8 Stream API Tutorial
@Order in Spring
Encode a String to UTF-8 in Java
Giới thiệu Design Patterns
Quick Guide to Spring MVC with Velocity
Java Program to Implement Shoelace Algorithm
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Implement PriorityBlockingQueue API
Spring Cloud – Bootstrapping
Lớp LinkedHashMap trong Java
Java Program to Implement Stein GCD Algorithm