Practice · Greedy · 2 of 4

Largest Sum of a Subarray

Given a list of integers nums, return the largest sum of a subarray: a non-empty run of consecutive items.

The list may hold negative numbers. When every number is negative, the answer is the largest single number.

Example 1

Input
nums = [3, -4, 5, -1, 2, -6, 1]
Output
6
[5, -1, 2] adds up to 6.

Example 2

Input
nums = [-3, -1, -2]
Output
-1
Every number is negative, so the best is the largest one on its own.

Constraints

  • nums holds 1 to 10⁴ numbers.
  • −10⁴ ≤ nums[i] ≤ 10⁴