Find the Maximum-Sum Contiguous Subarray
J.P. MorganSoftware Engineer II · OnsiteLast updated
Implement Kadane's algorithm to find the maximum sum of a non-empty contiguous subarray in linear time and constant auxiliary space, with proper handling for all-negative inputs and potential 64-bit integer overflow.
Problem Statement
You are given an array of integers nums. Your task is to find the contiguous non-empty subarray that has the largest sum and return that sum.
A subarray is a contiguous part of an array. The solution must operate in O(n) time complexity and use O(1) auxiliary memory. Pay special attention to edge cases such as arrays containing only negative numbers, and ensure calculations do not overflow standard 32-bit integer limits where applicable.
Function Signature
def max_subarray_sum(nums: list[int]) -> int:
pass
Input & Output Format
- Input: A list of integers
numswhere1 <= len(nums) <= 10^5. - Output: An integer representing the maximum possible sum of any contiguous, non-empty subarray.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- The accumulated sum can exceed the 32-bit signed integer range, so use 64-bit integer types if working in languages like C++ or Java (
long long/long).
Examples
Example 1
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.
Example 2
Input: nums = [-5, -2, -8, -1, -4]
Output: -1
Explanation: Because the subarray must be non-empty, the maximum sum is -1, corresponding to the single-element subarray [-1].
Edge Cases
- Arrays containing only a single element (the result must be that single element).
- Arrays containing exclusively negative values (the result is the maximum single negative number, not
0). - Arrays with large values where intermediate sums exceed
2^31 - 1.
Hints
Hint 1
Consider how the decision to either extend the current running subarray or start a new subarray at index `i` depends on the value of the running sum.
Hint 2
Initialize your tracking variables to the first element rather than 0 so that all-negative sequences are naturally supported.
Hint 3
Ensure your running sum and maximum sum variables use 64-bit storage if implementing in languages with fixed-width integer types.
Follow-up questions
- How would you return the actual starting and ending indices of the optimal subarray rather than just the sum?
- How would your approach change if the array represents a circular buffer where the subarray can wrap around the end of the array?
- Can this problem be solved using a divide-and-conquer strategy in O(n log n) time, and what advantages might that approach offer for parallel processing?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.