MediumNo. 0053

Maximum Subarray — LeetCode 53 Python Solution

Topics
Array, Divide and Conquer, Dynamic Programming
Reading time
2 min

The problem

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

Example

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.

Python solution

PythonSolution
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        ans = f = nums[0]
        for x in nums[1:]:
            f = max(f, 0) + x
            ans = max(ans, f)
        return ans

Complexity

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 53. Maximum Subarray is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 53. Maximum Subarray?

LeetCode 53. Maximum Subarray is rated Medium on LeetCode.

What is the time complexity of LeetCode 53. Maximum Subarray?

The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.

What is the space complexity of LeetCode 53. Maximum Subarray?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 53. Maximum Subarray cover?

LeetCode 53. Maximum Subarray is tagged Array, Divide and Conquer and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.