Maximum subarray (Kadane’s algorithm)
Medium TimeO(n) SpaceO(1)
Given nums, whose values may be negative, return the largest sum of any run of adjacent values — a subarray, not a subsequence. The run may not be empty, so when every value is negative the answer is the least negative one.
Examples
Example 1
- Input
- nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
- Output
64 + (−1) + 2 + 1= 6, and no other adjacent run reaches it.
Example 2
- Input
- nums = [-3, -1, -2]
- Output
- Every run of two or more sums lower, so the best is the single
-1-1on its own.
The Code
function maxSubArray(nums) {
let best = nums[0];
let current = nums[0];
for (let i = 1; i < nums.length; i++) {
current = Math.max(nums[i], current + nums[i]);
best = Math.max(best, current);
}
return best;
}
maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]);Done
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.
- House robber Rob a house and skip its neighbour, or skip to the next.