forked from Karan-Dhingra/Hacktoberfest-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKadane's Algorithm.java
51 lines (37 loc) · 1.13 KB
/
Kadane's Algorithm.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
42
43
44
45
46
47
48
49
50
import java.io.*;
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()); //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]);
}
Solution obj = new Solution();
//calling maxSubarraySum() function
System.out.println(obj.maxSubarraySum(arr, n));
}
}
}
// } Driver Code Ends
class Solution{
// arr: input array
// n: size of array
//Function to find the sum of contiguous subarray with maximum sum.
int maxSubarraySum(int arr[], int n){
int i,j,m=arr[0],sum=0;
for(i=0;i<n;i++){
sum=sum+arr[i];
if(sum<0)
sum=0;
else if(m<sum)
m=sum;
}
return m;
}
}