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:
String Processing with Apache Commons Lang 3
Tìm hiểu về xác thực và phân quyền trong ứng dụng
A Guide to Spring Cloud Netflix – Hystrix
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Java Program to Perform Insertion in a BST
Java Program to Implement CopyOnWriteArraySet API
Login For a Spring Web App – Error Handling and Localization
Date Time trong Java 8
A Guide to EnumMap
Lớp Collectors trong Java 8
@DynamicUpdate with Spring Data JPA
Java Program to Implement Borwein Algorithm
Setting the Java Version in Maven
Java Program to Implement HashTable API
Apache Commons Collections SetUtils
Finding Max/Min of a List or Collection
Java Program to Implement ArrayBlockingQueue API
Java Program to Check whether Graph is Biconnected
Convert XML to JSON Using Jackson
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Java Program to Implement Quick Sort with Given Complexity Constraint
Sắp xếp trong Java 8
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
A Guide to WatchService in Java NIO2
Hướng dẫn sử dụng String Format trong Java
Properties with Spring and Spring Boot
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Hashing a Password in Java
Java Program to Check whether Directed Graph is Connected using DFS
Limiting Query Results with JPA and Spring Data JPA
Java Program to Implement AA Tree
Returning Image/Media Data with Spring MVC