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:
A Guide to LinkedHashMap in Java
Spring MVC Content Negotiation
Spring Boot Annotations
Giới thiệu Google Guice – Injection, Scope
Sắp xếp trong Java 8
Spring Boot - Admin Client
Functional Interface trong Java 8
Hướng dẫn Java Design Pattern – Object Pool
A Guide to HashSet in Java
Spring Security and OpenID Connect
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Java – Delete a File
DynamoDB in a Spring Boot Application Using Spring Data
Java Program to Implement IdentityHashMap API
Java 8 and Infinite Streams
Hướng dẫn Java Design Pattern – Mediator
Java 8 Streams peek() API
Class Loaders in Java
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Delete a Particular Node in a Tree Without Using Recursion
A Guide to ConcurrentMap
Partition a List in Java
Autoboxing và Unboxing trong Java
Spring Boot - Eureka Server
Apache Commons Collections Bag
Limiting Query Results with JPA and Spring Data JPA
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Create the Prufer Code for a Tree
Java – Reader to InputStream
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Generating Random Numbers in a Range in Java
New Features in Java 13