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.
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
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
