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:
Getting Started with Stream Processing with Spring Cloud Data Flow
Remove All Occurrences of a Specific Value from a List
Java Program to Implement Rolling Hash
Giới thiệu thư viện Apache Commons Chain
Spring Data JPA @Query
Refactoring Design Pattern với tính năng mới trong Java 8
Java Program to Solve any Linear Equation in One Variable
Hashing a Password in Java
Java Program to Implement Pollard Rho Algorithm
Chuyển đổi từ HashMap sang ArrayList
Creating a Web Application with Spring 5
Hướng dẫn Java Design Pattern – Command
Java Program to Implement Stack
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Java Program to Find Transpose of a Graph Matrix
Java Program to Implement the Vigenere Cypher
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Implement Threaded Binary Tree
Java Program to Implement LinkedHashMap API
Comparing Objects in Java
Java Program to Solve Knapsack Problem Using Dynamic Programming
Java Program to Implement Gauss Seidel Method
Shuffling Collections In Java
Jackson vs Gson
Extract network card address
Xây dựng ứng dụng Client-Server với Socket trong Java
Using the Map.Entry Java Class
Hamcrest Collections Cookbook
Giới thiệu java.io.tmpdir
Convert Hex to ASCII in Java
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Getting Started with Custom Deserialization in Jackson