Java Program to Implement Kadane’s Algorithm

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.

  1. /*
  2.  *    Java Program to Implement Kadane Algorithm
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /* Class kadane */
  8. public class Kadane
  9. {
  10.     /* Function to largest continuous sum */
  11.     public int maxSequenceSum(int[] arr)
  12.     {        
  13.         int maxSoFar = arr[0], maxEndingHere = arr[0];
  14.  
  15.         for (int i = 1; i < arr.length; i++)
  16.         {
  17.             /* calculate maxEndingHere */
  18.             if (maxEndingHere < 0)
  19.                 maxEndingHere = arr[i];
  20.             else
  21.                 maxEndingHere += arr[i];
  22.  
  23.             /* calculate maxSoFar */
  24.             if (maxEndingHere >= maxSoFar)
  25.                 maxSoFar = maxEndingHere;
  26.         }
  27.         return maxSoFar;
  28.     }    
  29.     /* Main function */
  30.     public static void main (String[] args) 
  31.     {
  32.         Scanner scan = new Scanner(System.in);
  33.         System.out.println("Kadane Algorithm Test\n");
  34.         /* Make an object of Kadane class */
  35.         Kadane k = new Kadane();
  36.  
  37.         System.out.println("Enter size of array :");
  38.         int N = scan.nextInt();
  39.         /* Accept two 2d matrices */
  40.         System.out.println("Enter "+ N +" elements");
  41.         int[] arr = new int[N];
  42.         for (int i = 0; i < N; i++)
  43.             arr[i] = scan.nextInt();
  44.         int sum = k.maxSequenceSum(arr);
  45.         System.out.println("\nMaximum Sequence sum = "+ sum);
  46.  
  47.     }
  48. }

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.

👉 For weekly algorithms practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations