Problems

Maximum Subarray

medium
medium
arrays
dynamic-programming

Given an integer array nums, return the maximum sum of any non-empty contiguous subarray.

Input / output

  • Input: nums: integer[]
  • Output: integer maximum sum

Examples

  1. [-2,1,-3,4,-1,2,1,-5,4] returns 6 from [4,-1,2,1].
  2. [-5,-2,-8] returns -2; choosing no elements is not allowed.

Constraints

  • 1 <= nums.length <= 100,000
  • -10,000 <= nums[i] <= 10,000

Follow-up Can you derive Kadane's algorithm from the choice to extend the previous subarray or start a new one?

Examples

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
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.