forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KadanesAlgorithm.cpp
48 lines (47 loc) · 865 Bytes
/
KadanesAlgorithm.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
/*
Kadane's Algorithm
Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number)
which has the maximum sum and return its sum.
Example 1:
Input:
N = 5
Arr[] = {1,2,3,-2,5}
Output:
9
Explanation:
Max subarray sum is 9
of elements (1, 2, 3, -2, 5) which
is a contiguous subarray.
Example 2:
Input:
N = 4
Arr[] = {-1,-2,-3,-4}
Output:
-1
Explanation:
Max subarray sum is -1
of element (-1)
*/
#include<iostream>
using namespace std;
int maxSum(int a[], int n){
int ma = INT_MIN;
int max_th = 0;
for(int i=0; i<n; i++){
max_th = max_th+ a[i];
if(max_th>ma)
ma = max_th;
if(max_th<0)
max_th = 0;
}
return ma;
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
int sum= maxSum(a, n);
cout<<"Sum: "<<sum;
}