What is Kadane's algorithm?

Answer

Kadane's algorithm finds the maximum sum contiguous subarray in O(n) time and O(1) space. It's the optimal solution for the Maximum Subarray Sum problem (Leetcode 53). Key insight: at each position, either extend the previous subarray or start a new one at the current element — whichever is larger. Algorithm: maxSum = arr[0]; currentSum = arr[0]; for i from 1 to n-1: currentSum = max(arr[i], currentSum + arr[i]); maxSum = max(maxSum, currentSum);. This is a DP where dp[i] = maximum subarray sum ending at index i. If dp[i-1] < 0, don't extend (currentSum becomes arr[i]); if ≥ 0, extend. Time: O(n). Space: O(1). Track start/end indices for the actual subarray. Extensions: (1) Circular subarray maximum: max of (Kadane's result, totalSum - minimum subarray); (2) Maximum product subarray: track both max and min products (negatives flip); (3) 2D maximum sum subarray: fix columns, compress rows using prefix sums, apply Kadane's in O(n²×m) total; (4) K maximum non-overlapping subarrays. Applications: financial analysis (max profit period), signal processing, computer vision (maximum density rectangle).