> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Maximum Subarray Python Solution with Tests

> Tested Python solution for LeetCode 53 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 53, Medium. Topics: Array, Divide and Conquer, Dynamic Programming. [View on LeetCode](https://leetcode.com/problems/maximum-subarray/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 53   # by problem number
lcpy gen -s maximum_subarray   # by problem name
```

## Problem

Given an integer array `nums`, find the subarray with the largest sum, and return its sum.

### Examples

```
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
```

**Explanation:** The subarray \[4,-1,2,1] has the largest sum 6.

```
Input: nums = [1]
Output: 1
```

**Explanation:** The subarray \[1] has the largest sum 1.

```
Input: nums = [5,4,-1,7,8]
Output: 23
```

**Explanation:** The subarray \[5,4,-1,7,8] has the largest sum 23.

### Constraints

* `1 <= nums.length <= 10^5`
* `-10^4 <= nums[i] <= 10^4`

**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_subarray/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_subarray/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def max_sub_array(self, nums: list[int]) -> int:
        max_sum = current_sum = nums[0]

        for i in range(1, len(nums)):
            current_sum = max(nums[i], current_sum + nums[i])
            max_sum = max(max_sum, current_sum)

        return max_sum
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
