forked from puruagarwal1/hacktoberfest-2022-directory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKadane-algorithm.cpp
More file actions
41 lines (35 loc) · 795 Bytes
/
Kadane-algorithm.cpp
File metadata and controls
41 lines (35 loc) · 795 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int kodane(vector<int> arr){
int max_subArray_sum = 0;
int currentSubArraySum = 0;
for(int i = 0; i < arr.size(); i++){
currentSubArraySum = currentSubArraySum + arr[i];
if(currentSubArraySum > max_subArray_sum)
max_subArray_sum = currentSubArraySum;
if(currentSubArraySum < 0)
currentSubArraySum = 0;
}
return max_subArray_sum;
}
int main(){
int n;
vector<int> arr;
cout<<"Enter number of elements: ";
cin>>n;
for(int i = 0; i < n; i++){
int temp;
cin >> temp;
arr.push_back(temp);
}
cout<<"Largest subarray sum in inputted array = " << kodane(arr);
}
/*
Example Test cases
5
1 2 3 4 5
output: 15
5
3 1 -5 2 3
output: 5
*/