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 WebFlux Filters
Introduction to Spring MVC HandlerInterceptor
Beans and Dependency Injection
Overview of the java.util.concurrent
Guide to java.util.Formatter
Mapping Nested Values with Jackson
How To Serialize and Deserialize Enums with Jackson
Get and Post Lists of Objects with RestTemplate
Spring Security Custom AuthenticationFailureHandler
String Processing with Apache Commons Lang 3
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to Perform String Matching Using String Library
How to Get All Spring-Managed Beans?
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Implement Sieve Of Sundaram
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Java Program to Implement AVL Tree
Using JWT with Spring Security OAuth
Composition, Aggregation, and Association in Java
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Introduction to Java Serialization
Java Program to Implement LinkedBlockingDeque API
Class Loaders in Java
Jackson vs Gson
Java Program to Check whether Directed Graph is Connected using DFS
Java 8 Stream API Analogies in Kotlin
Introduction to Eclipse Collections
Collection trong java
Java Program to Perform Sorting Using B-Tree
Receive email using POP3
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Guide to java.util.concurrent.BlockingQueue