NeetCode #775LC-53MediumGreedyBlind 75NC 150NC 250
← Back to All Problems#775 · #53 · Maximum Subarray(最大子数组和)
📌 Problem Statement & Constraints
Given an integer array
nums, find the contiguous subarray (containing at least one number) with the largest sum and return that sum. Constraints: 1 <= nums.length <= 10^5, -10^4 <= nums[i] <= 10^4.💡 Core Algorithmic Approaches
- Kadane's algorithm: keep a running sum
curof the best subarray ending at the current index. - At each element, either extend the previous subarray (
cur + x) or restart fromx; take the larger. - Track the maximum value
curever reaches as the answer. - The restart option is what handles negative prefixes: any prefix that drags the sum down is simply dropped.
💻 Benchmark Python3 Implementation
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x) # extend or restart here
best = max(best, cur)
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single left-to-right pass.
💾 Space Complexity
O(1): two running scalars.
⚠️ Interview Pitfalls & Follow-ups
- Initialising
best = 0: for an all-negative array such as[-3, -1, -2]the answer is -1, but a zero initialisation would return 0. Initialise fromnums[0]. - Resetting
curto 0 whenever it goes negative: that also breaks all-negative input; usecur = max(x, cur + x)instead of an explicit reset. - Returning the subarray rather than the sum: this problem asks only for the sum.
- Using the divide-and-conquer solution: it is O(n log n) and far more code when the linear scan already works.