This is a Java Program to Implement Kadane Algorithm. Kadane algorithm is to used to obtain the maximum subarray sum from an array of integers.
Here is the source code of the Java Program to Implement Kadane Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/*
* Java Program to Implement Kadane Algorithm
*/
import java.util.Scanner;
/* Class kadane */
public class Kadane
{
/* Function to largest continuous sum */
public int maxSequenceSum(int[] arr)
{
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++)
{
/* calculate maxEndingHere */
if (maxEndingHere < 0)
maxEndingHere = arr[i];
else
maxEndingHere += arr[i];
/* calculate maxSoFar */
if (maxEndingHere >= maxSoFar)
maxSoFar = maxEndingHere;
}
return maxSoFar;
}
/* Main function */
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Kadane Algorithm Test\n");
/* Make an object of Kadane class */
Kadane k = new Kadane();
System.out.println("Enter size of array :");
int N = scan.nextInt();
/* Accept two 2d matrices */
System.out.println("Enter "+ N +" elements");
int[] arr = new int[N];
for (int i = 0; i < N; i++)
arr[i] = scan.nextInt();
int sum = k.maxSequenceSum(arr);
System.out.println("\nMaximum Sequence sum = "+ sum);
}
}
Kadane Algorithm Test Enter size of array : 9 Enter 9 elements -2 1 -3 4 -1 2 1 -5 4 Maximum Sequence sum = 6
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.
Related Posts:
- Check Java Books
- Practice Programming MCQs
- Apply for Java Internship
- Practice Information Technology MCQs
- Practice BCA MCQs