Skip to content

Commit bdd6b4f

Browse files
authored
Merge pull request #217 from RAUNAK-PANDEY/Raunak
Kadane's Algorithm using C++ #200
2 parents 8a9e454 + be664dc commit bdd6b4f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Arrays/Kadane's_Algorithm.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
2+
/* Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
3+
4+
5+
6+
Example 1:
7+
8+
Input:
9+
N = 5
10+
arr[] = {1,2,3,-2,5}
11+
Output:
12+
9
13+
Explanation:
14+
Max subarray sum is 9
15+
of elements (1, 2, 3, -2, 5) which
16+
is a contiguous subarray.*/
17+
#include<bits/stdc++.h>
18+
using namespace std;
19+
20+
21+
// } Driver Code Ends
22+
23+
24+
// Function to find subarray with maximum sum
25+
// arr: input array
26+
// n: size of array
27+
int maxSubarraySum(int arr[], int n){
28+
29+
// Your code here
30+
int i,maxCur=arr[0];
31+
int totalsum=arr[0];
32+
for(i=1;i<n;i++)
33+
{
34+
maxCur=max(arr[i],arr[i]+maxCur);
35+
if(maxCur>totalsum)
36+
{
37+
totalsum=maxCur;
38+
}
39+
}
40+
return totalsum;
41+
42+
}
43+
44+
// { Driver Code Starts.
45+
46+
int main()
47+
{
48+
int t,n;
49+
50+
cin>>t; //input testcases
51+
while(t--) //while testcases exist
52+
{
53+
54+
cin>>n; //input size of array
55+
56+
int a[n];
57+
58+
for(int i=0;i<n;i++)
59+
cin>>a[i]; //inputting elements of array
60+
61+
cout << maxSubarraySum(a, n) << endl;
62+
}
63+
}
64+
// } Driver Code Ends

0 commit comments

Comments
 (0)