Skip to content

Commit 658575b

Browse files
authored
Create Kadane's Algorithm
1 parent a3536b9 commit 658575b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Kadane's Algorithm

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// { Driver Code Starts
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
6+
// } Driver Code Ends
7+
8+
9+
// Function to find subarray with maximum sum
10+
// arr: input array
11+
// n: size of array
12+
int maxSubarraySum(int arr[], int n){
13+
14+
// Your code here
15+
int current=arr[0],overall=arr[0];
16+
for(int i=1;i<n;i++){
17+
if((current+ arr[i])<arr[i]){current=0;}
18+
current+=arr[i];
19+
if(current>overall){overall=current;}
20+
}
21+
return overall;
22+
}
23+
24+
// { Driver Code Starts.
25+
26+
int main()
27+
{
28+
int t,n;
29+
30+
cin>>t; //input testcases
31+
while(t--) //while testcases exist
32+
{
33+
34+
cin>>n; //input size of array
35+
36+
int a[n];
37+
38+
for(int i=0;i<n;i++)
39+
cin>>a[i]; //inputting elements of array
40+
41+
cout << maxSubarraySum(a, n) << endl;
42+
}
43+
}
44+
// } Driver Code Ends

0 commit comments

Comments
 (0)