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:
Custom HTTP Header with the HttpClient
Limiting Query Results with JPA and Spring Data JPA
Java Program to Implement vector
Thao tác với tập tin và thư mục trong Java
Giới thiệu về Stream API trong Java 8
Spring Boot - Thymeleaf
Tránh lỗi NullPointerException trong Java như thế nào?
Understanding Memory Leaks in Java
Java Program to Implement Caesar Cypher
Java 8 Collectors toMap
Java Program to Implement CountMinSketch
How to Convert List to Map in Java
Sắp xếp trong Java 8
Jackson – Marshall String to JsonNode
Java Program to Implement Min Heap
Documenting a Spring REST API Using OpenAPI 3.0
Comparing Long Values in Java
Java Program to Find Transitive Closure of a Graph
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Transaction Propagation and Isolation in Spring @Transactional
Guide to Apache Commons CircularFifoQueue
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Guide to the Java Queue Interface
Introduction to Netflix Archaius with Spring Cloud
Spring MVC and the @ModelAttribute Annotation
Receive email using POP3
Java Program to Implement Sieve Of Eratosthenes
Java Program to Perform Naive String Matching
A Guide to @RepeatedTest in Junit 5
Java Program to Generate Date Between Given Range
Fixing 401s with CORS Preflights and Spring Security
Guide to the Java Clock Class