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 Boot Security Auto-Configuration
Practical Java Examples of the Big O Notation
HTTP Authentification and CGI/Servlet
How to Remove the Last Character of a String?
Java Program to Implement Control Table
Guide to CopyOnWriteArrayList
Java Program to Implement Sorted Vector
New Features in Java 12
Guide to PriorityBlockingQueue in Java
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Decode a Message Encoded Using Playfair Cipher
Send an email with an attachment
Configuring a DataSource Programmatically in Spring Boot
Java Program to Check the Connectivity of Graph Using BFS
Java Program to implement Priority Queue
Giới thiệu về Stream API trong Java 8
Intro to Spring Boot Starters
JPA/Hibernate Persistence Context
Java – Combine Multiple Collections
Java Program to Represent Graph Using Adjacency Matrix
Spring REST API + OAuth2 + Angular
Java Program to Implement Sieve Of Atkin
Getting Started with Stream Processing with Spring Cloud Data Flow
Count Occurrences of a Char in a String
JUnit 5 for Kotlin Developers
Java Program to Show the Duality Transformation of Line and Point
Converting Between a List and a Set in Java
Spring 5 WebClient
Mix plain text and HTML content in a mail
Java Program to Implement Randomized Binary Search Tree
Spring Boot - Hystrix