Add Kadane's Algorithm to Java (#149)
* Kadane’s Algorithm * Update README.md * Kadane's Algorithmpull/153/head
parent
007e8a54a6
commit
183a3a660e
|
@ -19,3 +19,4 @@
|
|||
### Java
|
||||
|
||||
1. [Counting Inversions](java/count-inversions.java)
|
||||
2. [Kadane's Algorithm](java/Kadanes_Algorithm.java)
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue