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:
Quick Intro to Spring Cloud Configuration
Summing Numbers with Java Streams
Guide to Spring Cloud Kubernetes
Java Program to Implement Sorted Vector
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
The Java 8 Stream API Tutorial
A Guide to Spring Cloud Netflix – Hystrix
A Guide to TreeMap in Java
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Convert String to int or Integer in Java
Java Program to Represent Graph Using Adjacency Matrix
Java toString() Method
Java Program to Implement Euler Circuit Problem
Hướng dẫn Java Design Pattern – Dependency Injection
Convert Hex to ASCII in Java
Java Program to Find Inverse of a Matrix
Spring Web Annotations
Apache Commons Collections MapUtils
Java Program to Implement Weight Balanced Tree
Java Program to Implement Range Tree
JPA/Hibernate Persistence Context
A Guide to Concurrent Queues in Java
Logging a Reactive Sequence
Split a String in Java
Transaction Propagation and Isolation in Spring @Transactional
Spring Boot - Internationalization
Disable DNS caching
Display Auto-Configuration Report in Spring Boot
Java Program to Implement Bloom Filter
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Introduction to PCollections