Add Kadane's Algorithm to Java (#149)

* Kadane’s Algorithm

* Update README.md

* Kadane's Algorithm
pull/153/head
Aayush Jain 2021-04-10 01:08:44 +05:30 committed by GitHub
parent 007e8a54a6
commit 183a3a660e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -19,3 +19,4 @@
### Java ### Java
1. [Counting Inversions](java/count-inversions.java) 1. [Counting Inversions](java/count-inversions.java)
2. [Kadane's Algorithm](java/Kadanes_Algorithm.java)

View File

@ -0,0 +1,30 @@
// Java program to print largest contiguous array sum
import java.io.*;
import java.util.*;
class Kadane
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}