Algorithm-Day13-Maximum-Subarray-lc-53
🧩 Problem Description
Given an integer array nums
, find the subarray with the largest sum, and return its sum.
Example:
1 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] |
💡 Brute Force (Too Slow)
Try all subarrays and calculate the sum:
- Time complexity: O(n²) to O(n³)
- ❌ Not acceptable for large inputs
💡 Optimal Approach: Kadane’s Algorithm
✨ Key Idea
At each position i
, we decide:
- Either start a new subarray at
i
, or - Extend the previous subarray to include
nums[i]
This leads to the recurrence:
1 | currentMax = max(nums[i], currentMax + nums[i]) |
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n) – single pass
- Space Complexity: O(1) – no extra array needed
✍️ Summary
- Kadane’s Algorithm is a must-know for maximum subarray problems.
- It tracks both the current streak and global maximum.
- Often appears in interview problems and can be extended to 2D, circular arrays, etc.
If you understand this pattern, problems like “maximum profit”, “maximum product”, and “max subarray length” will feel much easier.