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:
Hướng dẫn Java Design Pattern – Mediator
Cài đặt và sử dụng Swagger UI
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
New Features in Java 9
Using Optional with Jackson
Spring MVC + Thymeleaf 3.0: New Features
Introduction to Spring Method Security
Introduction to Spring Data REST
Java Program to Find Transpose of a Graph Matrix
Tính đa hình (Polymorphism) trong Java
HTTP Authentification and CGI/Servlet
Compare Two JSON Objects with Jackson
So sánh ArrayList và Vector trong Java
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Write/Read cookies using HTTP and Read a file from the internet
Spring Boot - Actuator
Java Program to Construct an Expression Tree for an Prefix Expression
Working with Network Interfaces in Java
Java Program to Describe the Representation of Graph using Incidence Matrix
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Java Program to Print only Odd Numbered Levels of a Tree
Java Program to Implement Bit Array
Java IO vs NIO
Supplier trong Java 8
Java Program to Implement Min Hash
Java Program to Implement Levenshtein Distance Computing Algorithm
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Apache Commons Collections MapUtils
Iterating over Enum Values in Java
Composition, Aggregation, and Association in Java
Lập trình mạng với java
Java Program to Implement Miller Rabin Primality Test Algorithm
 
