Given an integer array
nums, find the subarray with the largest sum, and return its sum.Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 104
Let be the sum of the subarray . There is a integral insight in this question: take the array . Notice that , and . Since subarrays must be contiguous, any subarray containing is less than if we simply excluded it! In other words, if we find a subarray with , we should simply exclude it from the sum! Our algorithm thus works as follows:
def maxSubArray(self, nums: List[int]) -> int:
max_sum, agg_sum = nums[0], 0
for r in range(0, len(nums)):
if agg_sum < 0:
agg_sum = 0
agg_sum += nums[r]
max_sum = max(max_sum, agg_sum)
return max_sum
The non-constant time in the algorithm consists of the for loop. Each iteration is constant time (if statement which is a comparison, addition operation, and comparison/assignment operation), and there are iterations. Thus the algorithm takes time.
We only store constant space variables, so the algorithm takes space.