-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathkadane.java
More file actions
44 lines (23 loc) · 769 Bytes
/
kadane.java
File metadata and controls
44 lines (23 loc) · 769 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Main
{
// Function to find the maximum sum of a contiguous subarray
public static int kadaneNeg(int[] A)
{
int maxSoFar = Integer.MIN_VALUE;
int maxEndingHere = 0;
// traverse the given array
for (int i: A)
{
maxEndingHere = maxEndingHere + i;
maxEndingHere = Integer.max(maxEndingHere, i);
maxSoFar = Integer.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args)
{
int[] A = { -8, -3, -6, -2, -5, -4 };
System.out.println("The maximum sum of a contiguous subarray is " +
kadaneNeg(A));
}
}