Problem · Array
Maximum Subarray Sum
Learn this problemProblem statement
Given an integer array nums, return the largest possible sum of a non-empty contiguous subarray.
A subarray uses consecutive elements in their original order. You must select at least one element, even when all values are negative. Return the exact sum as a signed 64-bit integer.
Function
maxSubarraySum(nums: int[]) → longExamples
Example 1
nums = [4,-6,3,2,-1]return = 5The subarray [3,2] has the largest sum, 5. Extending it left or right decreases the sum.
Example 2
nums = [-4,-2,-7]return = -2The single-element subarray [-2] is optimal. Choosing no elements is not allowed.
Constraints
1 <= nums.length <= 20000-1000000 <= nums[i] <= 1000000