forked from usamajay/hacktoberfest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKadaneAlgo.cpp
43 lines (29 loc) · 785 Bytes
/
KadaneAlgo.cpp
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
#include<iostream>
#include<algorithm>
using namespace std;
/* KADANE's ALGORITHM */
/* Kadane's algorithm is able to find the maximum sum of a contiguous subarray in an array with a runtime of O(n). */
int main(){
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n],negative=0;
cout<<"Enter the elements of the array: ";
for(int i=0;i<n;i++){
cin>>arr[i];
if(arr[i]<0){
negative++;
}
}
int sum=0,ans=0;
if(negative == n){
ans=*max_element(arr,arr+n);
}
else {
for(int i=0;i<n;i++){
sum=max(arr[i],sum+arr[i]);
ans=max(ans,sum);
}
}
cout<<"Maximum sum: "<<ans<<"\n";
}