Maximum Subarray

Medium#53best subarray

You get an array of integers nums. Find the subarray with the largest sum and return that sum. A subarray is a block of elements in a row, with no gaps: from a single element up to the whole array. Our example: [3, -4, 2, -1, 5, -7, 4] — the answer is 6, from the subarray [2, -1, 5].

input
nums: an array of integers.
returns
The largest sum of a subarray: one or more numbers of nums in a row.
constraints
  • 1 ≤ nums.length ≤ 1000
  • −10⁴ ≤ nums[i] ≤ 10⁴
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number}
 */
function maxSubArray(nums) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.