Overview
Kadane's algorithm is functionally a DP algorithm optimized from O(N) space to O(1) space. It answers: "Should I add the current element to my existing sequence, or start a new sequence?"
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the contiguous subarray with the largest sum in O(N) time. The quintessential space-optimized DP algorithm.
Kadane's algorithm is functionally a DP algorithm optimized from O(N) space to O(1) space. It answers: "Should I add the current element to my existing sequence, or start a new sequence?"
Conceptually, `dp[i] = max(nums[i], nums[i] + dp[i-1])`. If `dp[i-1]` is negative, `nums[i]` on its own is better.
Instead of an array, we track `curSum`. If `curSum` ever drops below zero, it will mathematically drag down any future elements. So we reset it to 0.
Because the max subarray could be anywhere in the middle, we constantly update `maxSum` with the highest `curSum` we've ever seen.