forked from satarupa1/Hacktoberfest-satarupa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKadane's Algorithm .java
More file actions
47 lines (33 loc) · 1.01 KB
/
Kadane's Algorithm .java
File metadata and controls
47 lines (33 loc) · 1.01 KB
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
42
43
44
45
46
import java.io.*;
class Array {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases
while(t-->0){
//size of array
int n = Integer.parseInt(br.readLine().trim());
int arr[] = new int[n];
String inputLine[] = br.readLine().trim().split(" ");
//adding elements
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(inputLine[i]);
}
Kadane obj = new Kadane();
//calling maxSubarraySum() function
System.out.println(obj.maxSubarraySum(arr, n));
}
}
}
// } Driver Code Ends
class Kadane{
int maxSubarraySum(int arr[], int n){
int maxh = 0, maxf = Integer.MIN_VALUE;
for(int i=0; i<n; i++){
maxh+=arr[i];
maxf=Integer.max(maxh,maxf);
if(maxh<0)
maxh=0;
}
return maxf;
}
}