Skip to content

Commit 9391131

Browse files
authored
Merge pull request deutranium#222 from akshaygidwani404/master
Implemented Kadane's algorithm in java
2 parents 78f140e + 7cc094b commit 9391131

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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+
array[i]=sc.nextInt(); // input array elements
50+
}
51+
System.out.println("Maximum sum of subarray: "+obj.kadanesAlgorithm(array,n)); // output
52+
}
53+
}
54+
55+
/*Explanation:
56+
Here we will traverse the array and we will see whether all
57+
elements in the array are negative or not.
58+
59+
If all the elements are negative then we will simply take one element
60+
max1 and after iterating the array we will see if any other element has
61+
a value less than that (in a negative sense ) then we modify the value of max1.
62+
63+
Else there will mix of positive and negative elements. In that case, we will
64+
have one element max which will point to arr[0]. Then while traversing we will
65+
see if the sum of an incoming element with the existing sum variable is negative we
66+
will modify the value of the sum variable to 0 else we will traverse further.
67+
While traversing we will also keep the look at the value of max if anytime it
68+
is more than the sum we will modify it.
69+
70+
Time:O(N) Iterating loop.
71+
72+
Space:O(1) Not using any additional data structure.*/
73+
74+
75+
76+
77+
78+
79+
80+
81+

0 commit comments

Comments
 (0)