forked from junaidrahim/Hacktoberfest-KIIT-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kadane's Algorithm
39 lines (29 loc) · 906 Bytes
/
Kadane's Algorithm
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
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());
while(t-->0){
int n = Integer.parseInt(br.readLine().trim());
int arr[] = new int[n];
String inputLine[] = br.readLine().trim().split(" ");
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(inputLine[i]);
}
Kadane obj = new Kadane();
System.out.println(obj.maxSubarraySum(arr, n));
}
}
}
class Kadane{
int maxSubarraySum(int arr[], int n){
// Your code here
int res=arr[0];
int maxEnding=arr[0];
for(int i=1;i<n;i++){
maxEnding=Math.max(maxEnding+arr[i],arr[i]);
res=Math.max(res,maxEnding);
}
return res;
}
}