Introduction
The Maximum Subarray problem involves finding the contiguous subarray with the largest possible sum.
Given an integer array arr[], the task is to find:
- the contiguous subarray having maximum sum
- and return that maximum sum
This is one of the most important array problems and introduces the famous:
Kadane’s AlgorithmThis problem helps in understanding:
- dynamic programming intuition
- running sum optimization
- greedy decisions
- subarray processing
Example
Input: arr[] = [-2,1,-3,4,-1,2,1,-5,4]Output: 6Explanation:
Subarray: [4,-1,2,1] Sum = 6 This is the maximum possible subarray sum.
Input: arr[] = [5,4,-1,7,8] Output: 23 Explanation: Entire array forms the maximum subarray. 5 + 4 + (-1) + 7 + 8 = 23
Constraints
1 <= n <= 10^5-10^4 <= arr[i] <= 10^4
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all possible subarrays
- Calculate the sum of every subarray
- Track the maximum sum
This approach is easy to understand but repeated subarray calculations increase time complexity.
Steps
- Traverse all starting indices.
- Generate subarrays from each index.
- Calculate current subarray sum.
- Update maximum sum.
- Return final maximum sum.
Dry Run
Input Array:[-2,1,-3,4,-1,2,1,-5,4]
Start from -2: Current Sum = -2
Maximum Sum = -2
Add 1:
Current Sum = -1 Maximum Sum = -1
Continue traversal...
Start from 4:
Subarray:
[4,-1,2,1]
Current Sum = 6
Maximum Sum = 6
Final Result: 6
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
All possible subarrays are generated and processed.
Space Complexity: O(1) Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Kadane’s Algorithm)
Explanation
Kadane’s Algorithm efficiently finds the maximum subarray sum using a running sum approach.
The idea is:
- Maintain:
- current sum
- maximum sum
- If current sum becomes negative:
- discard it
- start new subarray
This works because:
- a negative running sum can never help future subarrays.
Steps
- Initialize:
- current_sum = 0
- max_sum = smallest value
- Traverse the array.
- Add current element to current_sum.
- Update maximum sum.
- If current_sum becomes negative:
- reset it to 0
- Return maximum sum.
Dry Run
Input Array:[-2,1,-3,4,-1,2,1,-5,4]
Initially:
current_sum = 0
max_sum = -∞
Traverse -2:
current_sum = -2
max_sum = -2
current_sum becomes negative
Reset current_sum = 0
Traverse 1: current_sum = 1
max_sum = 1
Traverse -3:
current_sum = -2
Reset current_sum = 0
Traverse 4:
current_sum = 4 max_sum = 4
Traverse -1:
current_sum = 3
Traverse 2:
current_sum = 5
max_sum = 5
Traverse 1: current_sum = 6
max_sum = 6
Final Result: 6
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each element is processed exactly once.
Space Complexity: O(1) Explanation: Only variables are used for tracking sums.