-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKadane's Algorithm
46 lines (35 loc) · 1.11 KB
/
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
40
41
42
43
44
45
46
//Kadane's Algorithm
import java.io.*;
import java.util.*;
class Main {
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) {
String line = br.readLine();
String[] tokens = line.split(" ");
ArrayList<Integer> array = new ArrayList<>();
for(String token : tokens) {
array.add(Integer.parseInt(token));
}
int[] arr = new int[array.size()];
int idx = 0;
for(int i : array) {
arr[idx++] = i;
}
Solution obj = new Solution();
System.out.println(obj.maxSubarraySum(arr));
}
}
}
class Solution {
int maxSubarraySum(int[] arr) {
int res = arr[0];
int maxEnding = arr[0];
for(int i = 1; i < arr.length; i++) {
maxEnding = Math.max(maxEnding + arr[i], arr[i]);
res = Math.max(res, maxEnding);
}
return res;
}
}