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:
Custom Cascading in Spring Data MongoDB
Guide to PriorityBlockingQueue in Java
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Tạo chương trình Java đầu tiên sử dụng Eclipse
Concatenating Strings In Java
DynamoDB in a Spring Boot Application Using Spring Data
Java InputStream to String
Check If Two Lists are Equal in Java
Java Streams vs Vavr Streams
Java Program to Implement Double Order Traversal of a Binary Tree
How to Get a Name of a Method Being Executed?
Introduction to Spring Boot CLI
Exception Handling in Java
Java Program to Implement Sieve Of Sundaram
Convert Character Array to String in Java
Weak References in Java
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Quick Guide to java.lang.System
New Features in Java 12
DistinctBy in the Java Stream API
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Java – Rename or Move a File
Error Handling for REST with Spring
LinkedList trong java
Java Program to Perform the Shaker Sort
Introduction to Using FreeMarker in Spring MVC
Converting Java Date to OffsetDateTime
Flattening Nested Collections in Java
Java Program to Implement the One Time Pad Algorithm
Extract links from an HTML page
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Spring Boot - Database Handling