Largest Sum of Any Contiguous Subarray

Implement maxSubarraySum

Given an array nums that may contain negative numbers, return the largest possible sum of any non-empty contiguous subarray. Trying every subarray works, but re-summing overlapping ranges from scratch throws away most of the previous work. Kadane's AlgorithmKadane's AlgorithmA single-pass technique for the maximum-subarray-sum problem: at each element, decide whether to extend the running subarray or restart from here, based on whether the running sum has gone negative. answers this in one pass: keep a running sum, and whenever it dips below zero, abandon it and start over at the next element — a negative running total can never help a future subarray, so restarting is always at least as good as carrying it forward.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

Example 2:

Input: nums = [1]

Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]

Output: 23

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴

nums =

[-2, 1, -3, 4, -1, 2, 1, -5, 4]