Skip to content

Commit 5b2f131

Browse files
committed
feat: Kadane's Algo - largests sum of contiguous subarray
1 parent 3bf78b8 commit 5b2f131

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <bits/stdc++.h>
2+
#define int long long
3+
#define INF 1000000000000000000
4+
#define MOD 1000000009;
5+
#define mid(l, u) ((l + u) / 2)
6+
#define rchild(i) (i * 2 + 2)
7+
#define lchild(i) (i * 2 + 1)
8+
using namespace std;
9+
10+
signed main() {
11+
int n;
12+
cin >> n;
13+
int a[n];
14+
for (int i = 0; i < n; i++)
15+
cin >> a[i];
16+
int dp[n];
17+
dp[0] = a[0];
18+
int ans = a[0];
19+
for (int i = 1; i < n; i++)
20+
ans = max(ans, (dp[i] = a[i] + max(dp[i - 1], (int)0)));
21+
cout << ans << endl;
22+
}
23+
24+
/*
25+
Sample Input:
26+
8
27+
-2 -3 4 -1 -2 1 5 -3
28+
Sample Output:
29+
7
30+
*/

0 commit comments

Comments
 (0)