Maximum Subarray
Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. **Examples:** ```typescript maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) // 6 (Subarray [4, -1, 2, 1]) maxSubArray([1]) // 1 maxSubArray([5, 4, -1, 7, 8]) // 23 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(1)
Using Kadane's algorithm, we iterate through the array of length n once. Each comparison is an O(1) arithmetic check, yielding an optimal O(n) runtime.
Follow-Up Questions Interviewers Ask About Maximum Subarray
- How would you return the actual subarray itself (indices start and end) instead of just the sum?
Track the starting index of the current subarray (`tempStart`). Whenever `currentSum` resets to `nums[i]`, update `tempStart = i`. Whenever `maxSum` is updated, record `bestStart = tempStart` and `bestEnd = i`. - Can this problem be solved using Divide and Conquer?
Yes! You can divide the array in half, recursively find the max subarray sum in left half, right half, and the max subarray crossing the midpoint. This yields an O(n log n) solution. - What if the array is circular (the end connects back to the beginning)?
In circular subarray (LeetCode 918), the max sum is either the standard Kadane max sum OR (total sum - minimum subarray sum). You compute both in O(n).
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.