Sitemap
HAOYU LEI

HAOYU LEI

Leetcode 53. Maximum Subarray

1 min readAug 18, 2018

This is a classic DP problem and is really good. Basically we follow a standard approach:

    Get HAOYU LEI’s stories in your inbox

    Join Medium for free to get updates from this writer.

  1. Define: let largest[i] be the largest sum of a contiguous subarray ending at position i of nums.
  2. Find recurrence equation: largest[i] = nums[i] + largest[i-1] if largest[i-1] > 0, and largest[i] = nums[i] otherwise, since it makes no sense to include nums[i] in previous contiguous subarray if previous sum is negative — I can simply start over from nums[i].
  3. Implement.

Pseudocode (indexing start from 1):

ALGORITHM maxSubArray(nums)
For i from 2 to len(nums) do
largest[i] = largest[i-1] > 0? nums[i] + largest[i-1] : nums[i]
return max(nums)

--

--