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 VList
Java Program to Solve Tower of Hanoi Problem using Stacks
Java Program to Implement Variable length array
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Java Program to implement Dynamic Array
Giới thiệu Google Guice – Injection, Scope
Java Program to Solve the 0-1 Knapsack Problem
Custom Cascading in Spring Data MongoDB
Java Program to Perform the Shaker Sort
Java Program to Decode a Message Encoded Using Playfair Cipher
Java Program to Represent Graph Using Adjacency Matrix
Hướng dẫn sử dụng Java Generics
Quick Guide to @RestClientTest in Spring Boot
Introduction to Spring Data MongoDB
Java Program to Perform Cryptography Using Transposition Technique
Converting Between an Array and a Set in Java
Java – Write a Reader to File
A Guide to Queries in Spring Data MongoDB
Spring Data MongoDB – Indexes, Annotations and Converters
Guide to Guava Table
Từ khóa throw và throws trong Java
Java Program to Implement Sieve Of Eratosthenes
A Quick JUnit vs TestNG Comparison
A Quick Guide to Spring MVC Matrix Variables
Cơ chế Upcasting và Downcasting trong java
Abstract class và Interface trong Java
Spring Boot - Enabling HTTPS
Java equals() and hashCode() Contracts
Lập trình mạng với java
Java Program to Implement Ternary Search Algorithm
Finding the Differences Between Two Lists in Java
Hướng dẫn sử dụng Java Annotation