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:
Tổng quan về ngôn ngữ lập trình java
Hướng dẫn sử dụng lớp Console trong java
Spring Boot Change Context Path
The Registration Process With Spring Security
What is Thread-Safety and How to Achieve it?
Guide to Java Instrumentation
Explain about URL and HTTPS protocol
Auditing with JPA, Hibernate, and Spring Data JPA
Java Program to Implement Queue using Linked List
Java Program to Perform Matrix Multiplication
Show Hibernate/JPA SQL Statements from Spring Boot
Receive email using IMAP
Build a REST API with Spring and Java Config
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Spring @Primary Annotation
Marker Interface trong Java
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Java Program to Implement Levenshtein Distance Computing Algorithm
Guide to Java 8 groupingBy Collector
Java Program to Find kth Largest Element in a Sequence
Java Program to Implement Sparse Array
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Spring Boot Configuration with Jasypt
Java Program to Implement Hash Trie
Guide to Apache Commons CircularFifoQueue
Guide to Java OutputStream
Debug a HttpURLConnection problem
Using JWT with Spring Security OAuth (legacy stack)
Guide to the Synchronized Keyword in Java
Date Time trong Java 8
Java Program to Check whether Directed Graph is Connected using BFS
Java – Reader to String