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:
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
File Upload with Spring MVC
Functional Interface trong Java 8
Spring Data JPA and Null Parameters
RestTemplate Post Request with JSON
DistinctBy in the Java Stream API
Java Program to Implement Pollard Rho Algorithm
Java Program to Implement Repeated Squaring Algorithm
Spring Data MongoDB Transactions
Tính đa hình (Polymorphism) trong Java
How to Replace Many if Statements in Java
Lớp Properties trong java
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Converting a Stack Trace to a String in Java
Java Program to Implement Interval Tree
Service Registration with Eureka
Java Program to Generate Randomized Sequence of Given Range of Numbers
Jackson vs Gson
A Guide to the Java ExecutorService
Java Program to Implement Find all Forward Edges in a Graph
Hướng dẫn Java Design Pattern – Decorator
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Java Multi-line String
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Implement Stack using Linked List
Concatenating Strings In Java
Multipart Upload with HttpClient 4
A Guide to JUnit 5
HashMap trong Java hoạt động như thế nào?
Spring Boot - Tomcat Deployment
Java Program to Perform Partial Key Search in a K-D Tree
Java – Byte Array to Reader