Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 53 · Kadane

Maximum Subarray

LeetCode 53 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

A negative prefix never helps a future subarray — reset it to 0.

मध्यमArrayDivide and ConquerDynamic Programming

मी 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. 1

    cur_sum = sum of the current candidate subarray; max_sum = best seen.

  2. 2

    Add each number to cur_sum and update max_sum before any reset.

  3. 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_sum
स्टेप-थ्रू लोड होत आहे…

Maximum 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.