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:
Xử lý ngoại lệ trong Java (Exception Handling)
Remove HTML tags from a file to extract only the TEXT
Spring Boot - Google OAuth2 Sign-In
Java Program to Implement Euler Circuit Problem
The Guide to RestTemplate
Spring Boot - Hystrix
Spring Security and OpenID Connect
Java Program to Implement Sparse Matrix
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Java Program to Check Cycle in a Graph using Graph traversal
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Lớp LinkedHashMap trong Java
Comparing Arrays in Java
Lập trình đa luồng với Callable và Future trong Java
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Hướng dẫn Java Design Pattern – Service Locator
Converting Between Byte Arrays and Hexadecimal Strings in Java
Spring Boot - Bootstrapping
Show Hibernate/JPA SQL Statements from Spring Boot
Login For a Spring Web App – Error Handling and Localization
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
JUnit 5 for Kotlin Developers
Java Program to Implement LinkedBlockingQueue API
Dockerizing a Spring Boot Application
Java Scanner hasNext() vs. hasNextLine()
Introduction to Spring Cloud Rest Client with Netflix Ribbon
Java Program to Create a Random Linear Extension for a DAG
Spring Security 5 for Reactive Applications
Iterating over Enum Values in Java
The Basics of Java Security
Apache Commons Collections Bag