forked from durgesh2001/hacktoberfest_demo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKadane's-Algorithm.cpp
More file actions
39 lines (34 loc) · 778 Bytes
/
Kadane's-Algorithm.cpp
File metadata and controls
39 lines (34 loc) · 778 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
// Below is an implementation of Kadane's Algo
// This Algo finds out Largest Sum of a Contiguous Subarray
// Time Complexity is O(n) and Space Compleity is O(1)
#include <bits/stdc++.h>
using namespace std;
int Kadane(int a[], int size)
{
int max2 = INT_MIN;
int max1 = 0;
for (int i = 0; i < size; i++)
{
max1 += a[i];
if (max2 < max1)
max2 = max1;
if (max1 < 0)
max1 = 0;
}
return max2;
}
int main()
{
int size;
cout << "Enter size of array: ";
cin >> size;
int a[size] = {0};
cout << "Enter elements of array: ";
for (int i = 0; i < size; i++)
{
cin >> a[i];
}
int ans = Kadane(a, size);
cout << "Maximum contiguous sum is " << ans;
return 0;
}