forked from Soumojitshome2023/DSA_Hacktoberfest_2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KadanesAlgo.java
41 lines (30 loc) · 1.06 KB
/
KadanesAlgo.java
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
37
38
39
40
41
import java.util.Scanner;
public class KadanesAlgo{
public static void main(String[] args) {
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array");
n=sc.nextInt();
int [] a= new int[n];
for (int i = 0;i<n ; i++){
System.out.print("Enter element "+(i+1)+": ");
a[i]=sc.nextInt();
}
System.out.println("The max subarray is "+maxsub(a));
}
// create function maxsubarray
static int maxsub(int a[]){
int max_so_far=a[0];
int max_ending_here=0;
for(int i=0;i<a.length;i++){
max_ending_here+=a[i];
if(max_ending_here>max_so_far){
max_so_far=max_ending_here;
}
if(max_ending_here<0){
max_ending_here=0;
}
}
return max_so_far;
}
}