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 5 Functional Bean Registration
How to use the Spring FactoryBean?
Apache Camel with Spring Boot
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Java Program to Decode a Message Encoded Using Playfair Cipher
Tips for dealing with HTTP-related problems
Hướng dẫn Java Design Pattern – Template Method
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Java Program to Convert a Decimal Number to Binary Number using Stacks
Test a REST API with Java
Handling Errors in Spring WebFlux
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Apache Commons Collections MapUtils
Tính kế thừa (Inheritance) trong java
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Quick Guide to Spring Bean Scopes
Assert an Exception is Thrown in JUnit 4 and 5
Spring Cloud AWS – Messaging Support
Java Program to Implement Hash Tables with Quadratic Probing
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
String Processing with Apache Commons Lang 3
Custom HTTP Header with the HttpClient
Spring Cloud Connectors and Heroku
Từ khóa throw và throws trong Java
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Using Optional with Jackson
Java Program to Implement Graph Structured Stack
Login For a Spring Web App – Error Handling and Localization
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Program to Implement the Bin Packing Algorithm
Java Program to Perform Searching in a 2-Dimension K-D Tree
Java Program to Perform Searching Based on Locality of Reference