Skip to content

Commit aa3443f

Browse files
Implementing Kadane's algorithm in java
Effectively explained and well commented java code for implementing Kadane's algorithm(Maximum subarray sum).
1 parent 8e3b6a2 commit aa3443f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Implementing Kadanes algorithm in java
2+
// Time complexity: O(n)
3+
// Space complexity: O(1)
4+
5+
import java.util.*; // Importing util package for getting user input(Scanner class)
6+
public class Main
7+
{
8+
int kadanesAlgorithm(int arr[], int n){
9+
int count=0; // count of negative elements
10+
int max1=arr[0];
11+
int max=0;
12+
for(int i=0;i<n;i++){
13+
if(arr[i]<0){
14+
count++;
15+
}
16+
}
17+
if(count==n){
18+
for(int i=1;i<n;i++){
19+
if(arr[i]>max1){
20+
max1=arr[i];
21+
}
22+
}
23+
return max1;
24+
}
25+
else{
26+
int sum=0;
27+
max=arr[0];
28+
for(int i=0;i<n;i++){
29+
sum=sum+arr[i];
30+
if(sum<0){ //if sum till current index gets less than 0, then reset it to 0
31+
sum=0;
32+
}
33+
if(sum>max){ //if sum till current index gets more than max, then set max to current sum
34+
max=sum;
35+
}
36+
}
37+
}
38+
return max;
39+
}
40+
public static void main(String[] args) { // main function
41+
Main obj=new Main();
42+
int n; // n: size of array
43+
Scanner sc=new Scanner(System.in);
44+
System.out.print("Enter array size: ");
45+
n=sc.nextInt();
46+
int[] array = new int[n]; // array: input array
47+
System.out.println("Enter array elements: ");
48+
for(int i=0; i<n; i++)
49+
{
50+
array[i]=sc.nextInt(); // input array elements
51+
}
52+
System.out.println("Maximum sum of subarray: "+obj.kadanesAlgorithm(array,n)); // output
53+
}
54+
}
55+
56+
/*Explanation:
57+
Here we will traverse the array and we will see whether all
58+
elements in the array are negative or not.
59+
60+
If all the elements are negative then we will simply take one element
61+
max1 and after iterating the array we will see if any other element has
62+
a value less than that (in a negative sense ) then we modify the value of max1.
63+
64+
Else there will mix of positive and negative elements. In that case, we will
65+
have one element max which will point to arr[0]. Then while traversing we will
66+
see if the sum of an incoming element with the existing sum variable is negative we
67+
will modify the value of the sum variable to 0 else we will traverse further.
68+
While traversing we will also keep the look at the value of max if anytime it
69+
is more than the sum we will modify it.
70+
71+
Time:O(N) Iterating loop.
72+
73+
Space:O(1) Not using any additional data structure.*/
74+
75+
76+
77+
78+
79+
80+
81+
82+

0 commit comments

Comments
 (0)