Fundamentals 4 min read

How to Solve LeetCode 53: Maximum Subarray Sum with Dynamic Programming

The article explains a dynamic‑programming approach to the classic “Maximum Subarray Sum” problem, defining dp[i] as the best sum ending at index i, deriving the recurrence dp[i]=max(dp[i‑1]+nums[i], nums[i]), initializing base cases, and providing complete Go code.

Nullbody Notes
Nullbody Notes
Nullbody Notes
How to Solve LeetCode 53: Maximum Subarray Sum with Dynamic Programming

Problem Statement

Given an integer array, find the contiguous sub‑array with the largest sum.

Dynamic‑Programming Idea

Define dp[i] as the maximum sum of a sub‑array that ends at index i. The overall answer is the maximum value among all dp[i].

Recurrence

For each i>0, dp[i] = max(dp[i‑1] + nums[i], nums[i]). This compares extending the previous best sub‑array with starting a new sub‑array at i.

Base Case

Since a sub‑array must contain at least one element, dp[i] is initialized to nums[i] for every i.

Final Result

After filling dp, iterate through it to obtain the greatest value, which is the required maximum sub‑array sum.

Complete Go Implementation

func maxSubArray(nums []int) int {
    // dp[i] stores the maximum sum of a sub‑array ending at i
    dp := make([]int, len(nums))

    // base case: each dp[i] starts as the element itself
    for k, _ := range dp {
        dp[k] = nums[k]
    }

    // compute dp for each element as the ending element
    for i := 0; i < len(nums); i++ {
        if i-1 >= 0 {
            dp[i] = max(dp[i], dp[i-1]+nums[i])
        }
    }

    result := math.MinInt
    // find the global maximum among all dp[i]
    for _, v := range dp {
        result = max(result, v)
    }
    return result
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmGodynamic programmingLeetCodemaximum subarray
Nullbody Notes
Written by

Nullbody Notes

Go backend development, learning open-source project source code together, focusing on simplicity and practicality.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.