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:
Apache Tiles Integration with Spring MVC
String Processing with Apache Commons Lang 3
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java Program to Implement Regular Falsi Algorithm
Hướng dẫn Java Design Pattern – Abstract Factory
The DAO with Spring and Hibernate
Apache Commons Collections Bag
Giới thiệu Google Guice – Injection, Scope
Một số nguyên tắc, định luật trong lập trình
REST Pagination in Spring
Java Program to Implement Cartesian Tree
Using JWT with Spring Security OAuth
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Spring Security 5 for Reactive Applications
Setting the Java Version in Maven
Autoboxing và Unboxing trong Java
Debug a HttpURLConnection problem
Java Program to Compare Binary and Sequential Search
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement PriorityBlockingQueue API
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Map Interface trong java
Using a Mutex Object in Java
Java Program to Implement the One Time Pad Algorithm
Hướng dẫn Java Design Pattern – DAO
Spring Boot Integration Testing with Embedded MongoDB
Removing all Nulls from a List in Java
Hướng dẫn sử dụng Java Generics