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 Doubly Linked List
Từ khóa static và final trong java
Java Program to Implement Warshall Algorithm
Java Program to Implement Bit Array
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Guide to UUID in Java
Java Program to Implement K Way Merge Algorithm
Java Program to Perform Matrix Multiplication
Java Program to Implement Sieve Of Eratosthenes
HttpClient with SSL
Java Program to Implement Euler Circuit Problem
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Tránh lỗi NullPointerException trong Java như thế nào?
Convert String to int or Integer in Java
Java Program to Implement Solovay Strassen Primality Test Algorithm
Creating Docker Images with Spring Boot
Spring Boot - Quick Start
Java Program to Implement Queue using Linked List
JPA/Hibernate Persistence Context
Testing an OAuth Secured API with Spring MVC
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
JUnit5 @RunWith
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Java Program to Implement CopyOnWriteArraySet API
A Guide to Java HashMap
Basic Authentication with the RestTemplate
Immutable Objects in Java
Spring Boot - Rest Template
Guide to the Fork/Join Framework in Java
Guide to java.util.concurrent.Locks
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Lớp HashMap trong Java