sagelearnai

Maximum Subarray

Difficulty: Medium · Pattern: Greedy · LeetCode #53

Return the largest possible sum of a non-empty contiguous subarray of nums.

Examples

text
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]  →  6    ([4, -1, 2, 1])
nums = [5, 4, -1, 7, 8]                 →  23   (the whole array)
nums = [-3, -1, -2]                     →  −1

Hints

  1. For each index, what's the best sum of a subarray that ends there?
  2. If the best sum ending at i−1 is negative, it can only hurt. Start over at i.

Approach

Kadane's algorithm: cur = best sum of a subarray ending at the current index = max(x, cur + x). Track the global maximum best. Initialize both with nums[0] so all-negative arrays work. O(n), O(1).

A divide-and-conquer O(n log n) solution exists (best crossing the midpoint), and is a common follow-up.

Complexity

Time: O(n). Space: O(1).

Python solution
def maxSubArray(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
JavaScript solution
function maxSubArray(nums) {
  let best = nums[0], cur = nums[0];
  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    best = Math.max(best, cur);
  }
  return best;
}