Maximum Subarray in Python

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # Step 1: Initialize max_current and max_global with the first element.
        max_current = max_global = nums[0]

        # Step 2: Iterate through the array starting from the second element.
        for num in nums[1:]:
            # Step 3: Update max_current for the current position.
            max_current = max(num, max_current + num)

            # Step 4: Update max_global if max_current is greater.
            max_global = max(max_global, max_current)

        # Step 5: Return max_global, the maximum subarray sum.
        return max_global

PrevNext