Problem 53

Abstract / Summary

Find the highest sum of a contiguous part of the given list of numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0053.py

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:

        if len(nums) == 1:
            return nums[0]

        sums = []
        total = 0
        for n in nums:
            total = max(total, 0) + n
            sums.append(total)

        return max(sums)
13 lines | 290 bytes | submitted August 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (10+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Divide And Conquer
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method maxSubArray that computes the maximum sum of any contiguous sub-array within a list of integers. The algorithm follows a single-pass approach, maintaining a running total that is reset to zero whenever it becomes negative, and records each intermediate total in a list. The final result is obtained by selecting the largest value from that list.

Key Steps

Handling a Single-Element Input

if len(nums) == 1:
    return nums[0]

When the input list contains exactly one element, the method returns that element immediately. This early exit avoids unnecessary processing and correctly handles the edge case where the only possible sub-array consists of the sole element, regardless of its sign.

Initializing Accumulators

sums = []
total = 0

Two variables are prepared before iterating over the input. sums will collect the cumulative totals after each iteration, while total holds the current running sum that may be extended or restarted.

Iterating Through the Numbers

for n in nums:
    total = max(total, 0) + n
    sums.append(total)

During each loop iteration the algorithm decides whether to continue the existing sub-array or start a new one. The expression max(total, 0) ensures that a negative running total is discarded, effectively resetting the sum to zero before adding the current element n. The updated total is then appended to sums, preserving the state after each step.

Selecting the Maximum Sum

return max(sums)

After processing all elements, the method returns the greatest value stored in sums. This value corresponds to the maximum sum achievable by any contiguous sub-array in the original list.

Edge Cases Addressed

The early return for a single-element list guarantees correct behavior when the input length is one, covering both positive and negative solitary values. The use of max(total, 0) inside the loop naturally handles sequences that contain long stretches of negative numbers; the running total is reset whenever it would otherwise decrease the potential sum, ensuring that sub-arrays starting after a negative dip are considered. Additionally, because every intermediate total is recorded, the algorithm correctly identifies the maximum sum even when the optimal sub-array consists of the final elements of the list.

Performance Optimizations

The method processes the input list in a single linear pass, updating the running total and storing each intermediate result without nested loops or repeated scans. By resetting the running total to zero instead of recomputing from scratch, the algorithm avoids redundant calculations. Storing the intermediate totals in a list allows the final maximum to be retrieved with a single built-in max call, which is efficiently implemented in Python. The early exit for a one-element list eliminates the overhead of list allocation and iteration for the simplest possible input.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of building blocks, and each block has a secret number written on it. Some numbers are big and happy, and some are small or even grumpy with minus signs. The goal is to pick a group of blocks that sit right next to each other so that all their numbers added together make the biggest treasure pile possible.

To do this, the computer walks down the row of blocks one by one. It keeps a running total of the numbers as it goes. If the total ever starts to get grumpy and drops below zero, the computer decides to leave that grumpy part behind and start fresh with the next block. It keeps track of every new total it finds by putting them into a special toy box. Once the computer has looked at every single block in the row, it peeks inside the toy box to see which total pile is the biggest one of all. That biggest pile is the winner.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.33 | σ = 0.86

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
61 links | 44 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Maximum Subarray - Amazon Coding Interview Question - Leetcode 53 - Python'
NeetCode 9 mins
Maximum Subarray - Amazon Coding Interview Question - Leetcode 53 - Python
YouTube video 'Maximum Subarray (Kadane's Algorithm) - Leetcode 53 - Dynamic Programming (Python)'
Greg Hogg 5 mins
Maximum Subarray (Kadane's Algorithm) - Leetcode 53 - Dynamic Programming (Python)
YouTube video 'Maximum Subarray - LeetCode 53 - Coding Interview Questions'
One Code Man 7 mins
Maximum Subarray - LeetCode 53 - Coding Interview Questions
YouTube video 'Maximum Subarray - LeetCode 53 - JavaScript'
AlgoJS 5 mins
Maximum Subarray - LeetCode 53 - JavaScript
YouTube video '[Java] Leetcode 53. Maximum Subarray [DP Subsequence #3]'
Eric Programming 10 mins
[Java] Leetcode 53. Maximum Subarray [DP Subsequence #3]
YouTube video 'Maximum Subarray - LeetCode 53 - Python'
Deepti Talesra 14 mins
Maximum Subarray - LeetCode 53 - Python
YouTube video 'Leetcode 53 - Maximum Subarray (JAVA Solution Explained!)'
LC Bear 6 mins
Leetcode 53 - Maximum Subarray (JAVA Solution Explained!)
YouTube video 'Maximum Subarray | LeetCode 53 | Theory + Python code'
Sai Anish Malla 9 mins
Maximum Subarray | LeetCode 53 | Theory + Python code
YouTube video 'LeetCode 53: Maximum Subarray | C# Solution |'
Code Scribbler 12 mins
LeetCode 53: Maximum Subarray | C# Solution |
YouTube video 'Maximum Subarray - LeetCode 53 - Kadane's Algorithm - Java'
Ali Bouali 11 mins
Maximum Subarray - LeetCode 53 - Kadane's Algorithm - Java
YouTube video 'Maximum Subarray | LeetCode  53 | From Brute Force to Kadane's Algorithm | Coders Camp'
Coders Camp 9 mins
Maximum Subarray | LeetCode 53 | From Brute Force to Kadane's Algorithm | Coders Camp
YouTube video '13. Maximum Subarray Sum (Kadane's Algorithm) | Array - Medium | Learn DSA | Leetcode 53'
Ayushi Sharma 10 mins
13. Maximum Subarray Sum (Kadane's Algorithm) | Array - Medium | Learn DSA | Leetcode 53
YouTube video '53. Maximum Subarray | JavaScript | LeetCode Data Structures | Detailed Explanation'
LeetCodeWithMonu 13 mins
53. Maximum Subarray | JavaScript | LeetCode Data Structures | Detailed Explanation
YouTube video 'Maximum Subarray | Leetcode 53 | Live coding session 🔥🔥🔥'
Coding Decoded 6 mins
Maximum Subarray | Leetcode 53 | Live coding session 🔥🔥🔥
YouTube video 'Solving LeetCode 53. Maximum Subarray | Kadane's Algorithm | Google | Amazon | Microsoft'
Code Harmony 12 mins
Solving LeetCode 53. Maximum Subarray | Kadane's Algorithm | Google | Amazon | Microsoft
YouTube video 'Kadane's Algorithm and the Maximum Subarray Problem - LeetCode 53'
Michael Vandi 10 mins
Kadane's Algorithm and the Maximum Subarray Problem - LeetCode 53
YouTube video 'Amazon Coding Interview Question | Leetcode 53 | Maximum Subarray'
WorkWithGoogler 7 mins
Amazon Coding Interview Question | Leetcode 53 | Maximum Subarray
YouTube video 'Maximum Subarray Python Solution - LeetCode #53'
Professor Oakes 5 mins
Maximum Subarray Python Solution - LeetCode #53
YouTube video 'Maximum Subarray - Leetcode 53 | Kadane's Algorithm in JavaScript'
Web Coder Abhishek 5 mins
Maximum Subarray - Leetcode 53 | Kadane's Algorithm in JavaScript
YouTube video 'Daily Leetcode #604: Nov 25, 2021 - 53. Maximum Subarray'
Programming Live with Larry 14 mins
Daily Leetcode #604: Nov 25, 2021 - 53. Maximum Subarray
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

15 similar problems

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality