Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The largest-sum subarray

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonMicrosoftBloomberg

Given a list of integers nums, return the largest sum of a non-empty contiguous subarray.

Examples

InputOutputWhy
nums = [-2,1,-3,4,-1,2,1,-5,4]6The subarray 4, −1, 2, 1.
nums = [5,4,-1,7,8]23The whole list.
nums = [-3,-1,-2]-1All negative: the best single element.

Constraints

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

Hints

Hint 1

Let end[i] be the best sum of a subarray ending exactly at i.

Hint 2

end[i] = max(end[i − 1] + nums[i], nums[i]): extend or restart.

Hint 3

The answer is the largest end[i]. Start from nums[0], not 0, so an all-negative list works.

Where people lose marks

  • Initialising the best to 0, which returns 0 for an all-negative list.
  • Resetting to 0 instead of to the current element.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.