templates/kadane.cpp
compilable
$cat templates/kadane
Kadane's Algorithm
Maximum contiguous subarray sum in O(n) time using linear DP.
#kadane#maximum-subarray#dp#linear
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll kadane(const vector<ll> &arr) {
ll best = 0, cur = 0;
for (ll x : arr) {
cur = max(x, cur + x);
best = max(best, cur);
}
return best;
}12 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Kadane's Algorithm
Finds the maximum sum of a contiguous subarray in .
Recurrence
Let = maximum subarray sum ending at index :
The answer is .
Notes
arr[0] and loop from index 1