Patterns / Intermediate
Kadane's Algorithm Visualizer
At each value, either extend the current subarray or start fresh here, whichever is bigger. Remember the best you have seen.
Start the Kadane's Algorithm simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(n) |
|---|---|
| Average time | O(n) |
| Worst time | O(n) |
| Extra space | O(1) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- Start with cur = best = -2.
[-2, 1, -3, 4, -1, 2, 1, -5, 4] - Starting fresh at 1 beats extending (-2 + 1 = -1).
- 1 is the new best.
- Extend: 1 + -3 = -2.
- Starting fresh at 4 beats extending (-2 + 4 = 2).
- 4 is the new best.
- Extend: 4 + -1 = 3.
- Extend: 3 + 2 = 5.
- 5 is the new best.
- Extend: 5 + 1 = 6.
- 6 is the new best.
- Extend: 6 + -5 = 1.
- Extend: 1 + 4 = 5.
- Done. The maximum subarray is [3..6] with sum 6.
Kadane's algorithm in Java, Python, C++, C and JavaScript
int maxSubArray(int[] a) {
int cur = a[0], best = a[0];
for (int i = 1; i < a.length; i++) {
cur = Math.max(a[i], cur + a[i]);
best = Math.max(best, cur);
}
return best;
}
def max_sub_array(a):
cur = best = a[0]
for i in range(1, len(a)):
cur = max(a[i], cur + a[i])
best = max(best, cur)
return best
int maxSubArray(const vector<int>& a) {
int cur = a[0], best = a[0];
for (int i = 1; i < (int)a.size(); i++) {
cur = max(a[i], cur + a[i]);
best = max(best, cur);
}
return best;
}
int maxSubArray(int a[], int n) {
int cur = a[0], best = a[0];
for (int i = 1; i < n; i++) {
cur = a[i] > cur + a[i] ? a[i] : cur + a[i];
if (cur > best) best = cur;
}
return best;
}
function maxSubArray(a) {
let cur = a[0], best = a[0];
for (let i = 1; i < a.length; i++) {
cur = Math.max(a[i], cur + a[i]);
best = Math.max(best, cur);
}
return best;
}In an interview
LeetCode 53, Maximum Subarray: the contiguous subarray with the largest sum.
This is the simplest dynamic programming problem: cur is "best sum ending at i". Saying that shows you understand DP.