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:
Java Program to Implement Ternary Search Algorithm
Check if a String is a Palindrome in Java
The Java 8 Stream API Tutorial
Introduction to Java Serialization
A Guide to Iterator in Java
How to Read a Large File Efficiently with Java
Hướng dẫn Java Design Pattern – Service Locator
Java Program to Find Maximum Element in an Array using Binary Search
Hướng dẫn Java Design Pattern – Interpreter
Java Program to Perform integer Partition for a Specific Case
New in Spring Security OAuth2 – Verify Claims
Kết hợp Java Reflection và Java Annotations
Logging in Spring Boot
Java Program to Implement Quick Sort with Given Complexity Constraint
REST Pagination in Spring
Giới thiệu luồng vào ra (I/O) trong Java
Lập trình đa luồng với CompletableFuture trong Java 8
Upload and Display Excel Files with Spring MVC
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Java Program to Describe the Representation of Graph using Incidence Matrix
Create a Custom Exception in Java
Custom Exception trong Java
Mapping a Dynamic JSON Object with Jackson
Java Program to Implement Binary Tree
Java Program to Implement Hamiltonian Cycle Algorithm
Java Program to Implement Weight Balanced Tree
Apache Commons Collections SetUtils
Spring @RequestParam Annotation
HashSet trong Java hoạt động như thế nào?
Converting Strings to Enums in Java
Introduction to Thread Pools in Java
Java Program to Implement the Checksum Method for Small String Messages and Detect