forked from yashasvi-goel/Basic-C-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkadanes.cpp
More file actions
33 lines (31 loc) · 848 Bytes
/
kadanes.cpp
File metadata and controls
33 lines (31 loc) · 848 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
/*Author: Sahil Kalamkar
Date: 13/10/2019
Program to calculate the maximum sum of a subarray.
The requirement of this algorithm is that there must be atleast one positive element in the array.
It does not work when we have all elements as negative.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int *input = new int[n];
for(int i=0;i<n;i++)cin>>input[i];
/*
Here we are maintaining two variables, currentSum to keep the track of the running sum
and maximumSum which gives us the maximum sum of a subarray until that point.
*/
int currentSum = 0;
int maximumSum = 0;
for(int i=0;i<n;i++)
{
currentSum+=input[i];
//Updation of maximumSum when currentSum exceeds maximumSum.
maximumSum=max(maximumSum,currentSum);
if(currentSum<0)
currentSum=0;
}
cout<<maximumSum<<'\n';
return 0;
}