π Kadaneβs Algorithm: Maximum Subarray
π Problem Description
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum, and return its sum.
Real-World Application
Used in Financial Analysis (max profit streak), Signal Processing, and Performance Tracking to identify the most beneficial continuous segment in a dataset.
π οΈ Constraints & Edge Cases
- \(1 \le nums.length \le 10^5\)
- \(-10^4 \le nums[i] \le 10^4\)
-
Edge Cases to Watch:
-
All negative numbers β return the maximum element
- Single element array
- Large alternating positive/negative values
π§ Approach & Intuition
The Aha! Moment
At every index, decide: π Extend the current subarray OR π Start a new subarray from here
π’ Brute Force (Naive)
Check all possible subarrays and compute their sums.
- Time Complexity: \(\mathcal{O}(N^2)\) (or \(\mathcal{O}(N^3)\) without prefix sum)
- Why it fails: Too slow for large inputs
π Optimal Approach (Kadaneβs Algorithm)
-
Initialize:
-
current_sum = nums[0] max_sum = nums[0]-
Iterate through array:
-
current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum)- Return
max_sum
π§© Visual Tracing
graph TD
A[Start at index 0] --> B{Extend or Restart?}
B -- "Extend (current + num)" --> C[Continue Subarray]
B -- "Restart (num only)" --> D[Start New Subarray]
C --> E[Update max_sum]
D --> E
π» Solution Implementation
β±οΈ Complexity Analysis
- Time Complexity: \(\mathcal{O}(N)\) β Single pass
- Space Complexity: \(\mathcal{O}(1)\) β Constant space
π€ Interview Toolkit
- Key Insight: Negative running sum hurts future results β reset
- Kadaneβs Rule:
current_sum = max(num, current_sum + num) - Handles All Negatives: Since we initialize with
nums[0] - Follow-up: Track subarray indices by storing start/end pointers