Skip to content

Maximum Subarray

Given an integer array nums, find the subarray with the largest sum and return its sum. A subarray is a contiguous non-empty sequence of elements within an array.

InputOutputExplanation
[-2, 1, -3, 4, -1, 2, 1, -5, 4]6Subarray [4, -1, 2, 1] has the largest sum of 6
[5, 4, -1, 7, 8]23Entire array [5, 4, -1, 7, 8] has the sum of 23
[-1]-1Only one element, so return that element
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
ApproachTimeSpaceBest When
Brute ForceO(n²)O(1)Learning, tiny arrays
KadaneO(n)O(1)General case — fast and simple
Divide & ConquerO(n log n)O(log n)Interview discussion
  • Pick Kadane for the optimal interview solution — it is simple, O(n), and elegant.
  • Pick Brute Force if you are learning how to think about subarrays.
  • Pick Divide & Conquer if you want to understand the recursive pattern or are discussing trade-offs.
Best For Speed
Kadane
O(n) time · O(1) space
Learn Pattern
Brute Force
O(n²) time · O(1) space
Divide & Conquer
Recursive
O(n log n) time · O(log n) space
✓ Simple

Check every possible subarray by examining all pairs of start and end indices. For each starting position, consider all possible ending positions and track the maximum sum found.

⏱ Time O(n²) All pairs checked 💾 Space O(1) Constant
maximum_subarray_brute_force.py
from typing import List
def maximum_subarray_brute_force(nums: List[int]) -> int:
"""
Maximum Subarray - Brute Force approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
Section titled “Approach 2: Kadane’s Algorithm (Recommended)”
★ Recommended

Use dynamic programming to track the maximum sum ending at the current position. If adding the current element to the previous maximum sum is worse than starting fresh, restart from the current element.

⏱ Time O(n) Single pass 💾 Space O(1) Constant
maximum_subarray_kadane.py
from typing import List
def maximum_subarray_kadane(nums: List[int]) -> int:
"""
Maximum Subarray - Kadane approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
🎯 Interview Favourite

Divide the array into two halves and recursively find the maximum subarray in each half. The answer is either in the left half, right half, or crosses the midpoint.

⏱ Time O(n log n) Recursive depth 💾 Space O(log n) Call stack
maximum_subarray_divide_and_conquer.py
from typing import List
def maximum_subarray_divide_and_conquer(nums: List[int]) -> int:
"""
Maximum Subarray - Divide And Conquer approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass