forked from Harshita-Kanal/Data-Structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cpp-KadaneAlgorithm.cpp
50 lines (32 loc) · 1.08 KB
/
Cpp-KadaneAlgorithm.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
44
45
46
47
48
49
50
/*
Kadane's Algorithm
Kadane's is generally used for finding the max Subarray from a given array.
-------------------------Time and Space------------------------
Time - O(n)
Space - O(1)
---------------------------------------------------------------
*/
#include<bits/stdc++.h>
using namespace std;
int maxSubArray(vector<int>& nums) {
int currentSum =nums[0], totalSum = nums[0];
for(int i=1; i<nums.size(); i++) {
//Current max sum is either the current element OR current element + Previous Maximum subarray)
currentSum = max(nums[i], currentSum+nums[i]);
//If the current maximum array sum is greater than the global total. Update it
totalSum = max(totalSum, currentSum);
}
return totalSum;
}
int main()
{
ios_base::sync_with_stdio(false),cin.tie(NULL);
// the number of terms in the array
int n=0;
cin>>n;
vector<int> v(n);
for(int i = 0 ; i < n ; i++) cin >> v[i];
// the nth fibonacci term
cout<<maxSubArray(v);
return 0;
}