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:
Java Program to Check Whether Graph is DAG
Giới thiệu HATEOAS
Java Program to Implement the Monoalphabetic Cypher
The DAO with JPA and Spring
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Java Program to Perform integer Partition for a Specific Case
Java Program to Implement RoleUnresolvedList API
CyclicBarrier in Java
Guide to Guava Multimap
Java Program to Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
Java – Reader to InputStream
An Intro to Spring Cloud Task
Extract links from an HTML page
Use Liquibase to Safely Evolve Your Database Schema
Java Program to Implement Iterative Deepening
Java – Rename or Move a File
Java Byte Array to InputStream
Giới thiệu java.io.tmpdir
A Guide to Java HashMap
The Registration Process With Spring Security
Spring Cloud Bus
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Java – String to Reader
Guide to Apache Commons CircularFifoQueue
Một số từ khóa trong Java
Composition, Aggregation, and Association in Java
Sử dụng CountDownLatch trong Java
Java Program to Implement Coppersmith Freivald’s Algorithm
Check If a String Is Numeric in Java
Disable DNS caching
A Guide to the ViewResolver in Spring MVC
Converting between an Array and a List in Java