Maximum Subarray - Python Solution

1. Introduction

The "Maximum Subarray" problem is a classic in computer science, often solved using dynamic programming. It involves finding a contiguous subarray within a one-dimensional array of numbers which has the largest sum. This problem is fundamental in the study of algorithmic techniques for optimizing sums within arrays.


Given an integer array nums, the task is to find the subarray that has the largest sum and return this sum. The subarray must contain at least one number from the array.

2. Solution Steps

1. Initialize two variables: max_current and max_global, both set to the first element of the array.

2. Iterate through the array starting from the second element.

3. For each element, update max_current to be either the current element or the sum of max_current and the current element, whichever is larger.

4. Update max_global if max_current is greater than max_global.

5. Repeat steps 3 and 4 until the end of the array.

6. max_global will hold the largest sum of any subarray by the end of the iteration.

3. Code Program

def maxSubArray(nums):
    if not nums:
        return 0

    max_current = max_global = nums[0]

    for num in nums[1:]:
        max_current = max(num, max_current + num)
        max_global = max(max_global, max_current)

    return max_global

# Example Usage
print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))  # Output: 6
print(maxSubArray([1]))                     # Output: 1
print(maxSubArray([5,4,-1,7,8]))            # Output: 23




1. Initialization: Start with the first element as the initial max_current and max_global.

2. Iterative Comparison: Traverse the array, comparing each element with the sum of the element and max_current.

3. Current Maximum: max_current keeps track of the maximum subarray sum ending at the current position.

4. Global Maximum: max_global keeps the record of the maximum sum encountered so far.

5. Dynamic Programming: This approach utilizes dynamic programming to optimize the calculation.

6. Efficient Solution: Achieves O(n) time complexity, where n is the length of the array.

7. Practical Application: Useful in various real-world scenarios where maximum sum calculations are required, like financial analyses.