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:
How to Iterate Over a Stream With Indices
Hướng dẫn Java Design Pattern – Intercepting Filter
Returning Image/Media Data with Spring MVC
Java Program to Implement the Hill Cypher
Apache Commons Collections MapUtils
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Handling Errors in Spring WebFlux
Java Program to Implement TreeSet API
Java Program to Implement Repeated Squaring Algorithm
@Lookup Annotation in Spring
Java Program to Implement the RSA Algorithm
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Cachable Static Assets with Spring MVC
Spring Autowiring of Generic Types
Java Program to Implement K Way Merge Algorithm
Guide to System.gc()
New Features in Java 9
Java Program to implement Dynamic Array
Spring 5 Testing with @EnabledIf Annotation
Recommended Package Structure of a Spring Boot Project
Java Program to Implement Gabow Algorithm
Hướng dẫn Java Design Pattern – Null Object
Java Copy Constructor
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Perform the Sorting Using Counting Sort
Introduction to Project Reactor Bus
Spring WebClient Requests with Parameters
Converting String to Stream of chars
Java Program to Implement Shoelace Algorithm
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Câu lệnh điều khiển vòng lặp trong Java (break, continue)