1. First state
The best subarray ending at index 0 is nums[0].
let bestEndingHere = nums[0]Typorithm · easy
Step 1 of 8 · intro card
Dynamic Programming
Maximum Subarray uses Kadane's DP: keep the best sum ending here and the best sum seen so far.
A negative previous sum may hurt the current subarray.
The transition chooses extend or restart.
A global best stores the answer across all endings.
State: best sum ending at i.
Transition: max(nums[i], previous + nums[i]).
Answer: best global sum.
Time O(n), space O(1).
function maxSubArray(nums) {
let bestEndingHere = nums[0];
let bestSoFar = nums[0];
for (let i = 1; i < nums.length; i++) {
bestEndingHere = Math.max(nums[i], bestEndingHere + nums[i]);
bestSoFar = Math.max(bestSoFar, bestEndingHere);
}
return bestSoFar;
}Connect each part of the code to the concept before you type.
The best subarray ending at index 0 is nums[0].
let bestEndingHere = nums[0]Either start fresh at nums[i] or extend the previous subarray.
bestEndingHere = Math.max(nums[i], bestEndingHere + nums[i])Track the best subarray seen anywhere.
bestSoFar = Math.max(bestSoFar, bestEndingHere)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputNumbers -2,1,-3,4,-1,2,1,-5
Follow temporary values, local state and supporting structures at this step.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state