Blind 75
61 / 75Free practice

Maximum Subarray

Medium · Greedy

Jump to code

Find the greatest sum of a nonempty contiguous subarray within a nonempty integer array.

Examples

Example 1

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

Output: 6

Example 2

nums = [1]

Output: 1

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
Need a hint?

A negative running prefix can only hurt the next segment.

Asked in real interviews

Candidates reported versions of Maximum Subarray from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    -2,
    1,
    -3,
    4,
    -1,
    2,
    1,
    -5,
    4
  ]
]
Expected
6
Case 2
Input
[
  [
    1
  ]
]
Expected
1
Case 3
Input
[
  [
    5,
    4,
    -1,
    7,
    8
  ]
]
Expected
23
Case 4
Input
[
  [
    -3,
    -2,
    -5
  ]
]
Expected
-2
Case 5
Input
[
  [
    0,
    0,
    0
  ]
]
Expected
0

Drafts are saved per language in this browser when storage is available.