Python 1186.py
class Solution:
def maximumSum(self, arr: List[int]) -> int:
result = arr[0]
# current subarray with zero or one deletion
zero = arr[0]
one = arr[0]
for a in arr[1 :]:
# append or delete
one = max(one + a, zero)
# append
zero += a
# restart
one = max(one, a)
zero = max(zero, a)
result = max(result, zero, one)
return result
Difficulty
and has an acceptance rate of about 49% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
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.
Code Walkthrough
Overview
The provided Solution class implements a method maximumSum that computes the largest possible sum of a subarray when at most one element may be removed from that subarray. The algorithm processes the input list arr in a single left-to-right pass, maintaining two running aggregates: one for subarrays that have not used the deletion opportunity (zero) and one for subarrays that have already applied a deletion (one). The final answer is the greatest value observed among these aggregates throughout the traversal.
Core Logic
Initialization
result = arr[0]
zero = arr[0]
one = arr[0]
The variables are seeded with the first element of the array. result stores the best sum found so far. zero represents the maximum sum of a subarray ending at the current position that has performed zero deletions. one represents the maximum sum of a subarray ending at the current position that has performed exactly one deletion (or none if the deletion is applied to the current element).
Iteration Over the Remaining Elements
for a in arr[1:]:
# append or delete
one = max(one + a, zero)
# append
zero += a
# restart
one = max(one, a)
zero = max(zero, a)
result = max(result, zero, one)
The loop processes each element a after the first. The steps are:
-
Extending a subarray with a deletion already used -
one + aadds the current element to a subarray that already contains a deletion. -
Using the deletion on the current element -
zero(the best sum without deletion up to the previous element) becomes a candidate foronebecause deleting the current element yields the same sum as the previouszero. The expressionmax(one + a, zero)selects the better of extending the deleted subarray or deleting the current element. -
Extending a subarray without any deletion -
zero += asimply adds the current element to the ongoing non-deleted subarray. -
Starting a new subarray - The two
maxcalls after the extensions compare the current aggregates with the value of the element alone (a). This step restarts the subarray when the accumulated sum becomes detrimental, ensuring that bothzeroandonenever drop below the value of a single element. -
Updating the global optimum -
resultis refreshed with the maximum among the previous best, the currentzero, and the currentone.
Return Value
return result
After the loop finishes, result holds the maximum achievable sum under the constraint of at most one deletion.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions:
-
Single-element input - The initialization sets
result,zero, andoneto the sole element, and the loop body is skipped, returning that element directly. -
All negative numbers - Because each aggregate is compared with the current element (
a) after every iteration, the method can choose a subarray consisting of a single, least-negative element. The deletion option does not force inclusion of additional elements, so the answer remains the maximum (least negative) value. -
Deletion of the first element - When the optimal solution removes the first element, the algorithm captures this scenario because
onecan be set tozero(which initially equals the first element) before any addition, effectively treating the first element as deleted. -
Deletion of the last element - The update
one = max(one + a, zero)allows the last element to be omitted by taking thezerovalue from the previous iteration, thereby representing a subarray that ends one position earlier but has already used its deletion. -
No deletion needed - If the best subarray does not require any removal, the
zeroaggregate will dominateone, andresultwill reflect the standard maximum subarray sum.
Performance Optimizations
The implementation achieves high efficiency through several deliberate choices:
-
Constant-space state - Only three scalar variables (
zero,one,result) are maintained regardless of input size. This eliminates the need for auxiliary arrays or data structures, keeping memory usage minimal. -
Single pass - All necessary information is derived in one linear scan. By updating
zeroandonein place, the algorithm avoids recomputation of intermediate sums. -
In-place max operations - The use of the built-in
maxfunction for each decision point provides fast branching without explicit conditional statements, which can be beneficial for interpreter optimizations. -
Early restart logic - The immediate comparison of each aggregate with the current element (
a) prevents the accumulation of large negative prefixes. This early reset reduces the number of arithmetic operations on values that would later be discarded, contributing to faster convergence on the optimal sum. -
Avoidance of redundant calculations - The expression
one = max(one + a, zero)reuses the previously computedzerovalue, eliminating the need to recompute the sum of the subarray without deletion.
Collectively, these choices ensure that the method runs in linear time with a tiny memory footprint, making it suitable for large input arrays.
ELI5 - Simplified Explanation
Imagine a long train track made of many number blocks. The goal is to find the biggest group of blocks that are sitting right next to each other in a line.
To help solve this, there are two special containers. The first container keeps track of the biggest sum found so far if every block stays exactly where it is. The second container is like a magic box that allows one single block to be skipped over if hiding it makes the total sum of the other blocks even bigger.
The computer travels along the train track one block at a time. Every time it lands on a new block, it checks if adding that block to the current group makes the total larger. If the total gets smaller, the computer can decide to start a brand new group right there with just that single block instead.
As it moves along, it looks at both the magic box and the regular container to see which group has the highest score. It keeps the best score it has found throughout the entire trip in a final place so it remembers the winner when the track ends.
Code Quality
Complexity Analysis
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
Other Solutions
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 | Go | Rust | TS | |||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 873: Length of Longest Fibonacci Subsequence
- problem 963: Minimum Area Rectangle II
- problem 1049: Last Stone Weight II
- problem 1300: Sum of Mutated Array Closest to Target
Extra
- 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