Maximum Subarray
LeetCode 53 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
A negative prefix never helps a future subarray — reset it to 0.
నేను Maximum Subarray (LeetCode 53) ను ఇలా పరిష్కరించాను — Kadane ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Walk through the array carrying a running sum. Whenever that running sum turns negative it can only drag down whatever comes next, so throw it away and start fresh. The best sum seen along the way is the answer (Kadane's algorithm).
Approach
- 1
cur_sum = sum of the current candidate subarray; max_sum = best seen.
- 2
Add each number to cur_sum and update max_sum before any reset.
- 3
If cur_sum drops below 0, reset it to 0 so the next element starts a new subarray.
నేను ఎలా పరిష్కరించాను
Kadane's algorithmPythonO(n) time · O(1) space
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = float("-inf")
cur_sum =0
for num in nums:
cur_sum+=num
max_sum = max(max_sum,cur_sum)
if cur_sum<0:
cur_sum=0
return max_sumMaximum Subarray — తరచూ అడిగే ప్రశ్నలు
Maximum Subarray వెనుక ఉన్న intuition ఏమిటి?
Walk through the array carrying a running sum. Whenever that running sum turns negative it can only drag down whatever comes next, so throw it away and start fresh. The best sum seen along the way is the answer (Kadane's algorithm).
Maximum Subarray (LeetCode 53) ను ఎలా పరిష్కరించాలి?
1. cur_sum = sum of the current candidate subarray; max_sum = best seen. 2. Add each number to cur_sum and update max_sum before any reset. 3. If cur_sum drops below 0, reset it to 0 so the next element starts a new subarray.
Maximum Subarray యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Kadane's algorithm.)
Maximum Subarray లో సాధారణ పొరపాట్లు ఏమిటి?
Update max_sum before resetting, otherwise an all-negative array returns 0 instead of its largest element.