Problem 1186

Abstract / Summary

Find the highest sum of a contiguous subarray when you can remove at most one element from it.

Note

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

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
20 lines | 502 bytes | submitted May 10, 2024 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • 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 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 + a adds 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 for one because deleting the current element yields the same sum as the previous zero. The expression max(one + a, zero) selects the better of extending the deleted subarray or deleting the current element.

  • Extending a subarray without any deletion - zero += a simply adds the current element to the ongoing non-deleted subarray.

  • Starting a new subarray - The two max calls 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 both zero and one never drop below the value of a single element.

  • Updating the global optimum - result is refreshed with the maximum among the previous best, the current zero, and the current one.

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, and one to 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 one can be set to zero (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 the zero value 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 zero aggregate will dominate one, and result will 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 zero and one in place, the algorithm avoids recomputation of intermediate sums.

  • In-place max operations - The use of the built-in max function 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 computed zero value, 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

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 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++
28 links | 15 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   May 10, 2024

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