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:
Remove All Occurrences of a Specific Value from a List
How to Store Duplicate Keys in a Map in Java?
StringBuilder vs StringBuffer in Java
Introduction to Spring Cloud CLI
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Find the Minimum value of Binary Search Tree
A Guide to WatchService in Java NIO2
Explain about URL and HTTPS protocol
A Guide to Java HashMap
Reactive WebSockets with Spring 5
Java Program to Perform the Sorting Using Counting Sort
Java Program to Solve Tower of Hanoi Problem using Stacks
HandlerAdapters in Spring MVC
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Remove HTML tags from a file to extract only the TEXT
RestTemplate Post Request with JSON
Java 9 Stream API Improvements
Giới thiệu Google Guice – Dependency injection (DI) framework
Java Program to implement Priority Queue
Java Program to Implement Queue using Linked List
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Java Multi-line String
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Java Program to Solve the 0-1 Knapsack Problem
Deque và ArrayDeque trong Java
Java Program to Implement Binary Heap
Java Program to Implement LinkedHashSet API
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Compute DFT Coefficients Directly
Java Program to Implement HashSet API
Spring Data – CrudRepository save() Method
How to Find an Element in a List with Java