Problem 1749

Abstract / Summary

Given an array of integers, find the largest possible absolute value of the sum of any contiguous subarray.

Note

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

Python 1749.py

class Solution:
    def maxAbsoluteSum(self, nums: List[int]) -> int:
        result = 0

        # 1,000,000th problem based on Kadane's algorithm
        high = low = 0
        for n in nums:
            high   = max(n, high + n)
            low    = min(n, low  + n)
            result = max(result, abs(high), abs(low))

        return result
12 lines | 359 bytes | submitted January 19, 2024 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (200k+ 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 implementation defines a Solution class with a single method maxAbsoluteSum. The method receives a list of integers and returns the maximum absolute value that can be obtained from any sub-array sum. The algorithm is a compact adaptation of Kadane’s technique, simultaneously tracking the best positive sub-array sum and the most negative sub-array sum while updating the overall answer with the larger absolute value.

Key Steps

Initialization

The method starts by setting the accumulator variables to zero. result holds the best absolute sum seen so far, while high and low represent the current maximum and minimum sub-array sums ending at the current position.

result = 0
high = low = 0

Iteration Over the Input

A single pass over nums processes each element n. For each element the algorithm decides whether to extend the previous sub-array or to start a new sub-array at the current element. This decision is made separately for the maximum and minimum sums.

for n in nums:
    high = max(n, high + n)
    low  = min(n, low + n)
  • high = max(n, high + n) chooses the larger between starting a new sub-array with n alone or extending the previous maximum sub-array by adding n.
  • low = min(n, low + n) mirrors the logic for the minimum sub-array, selecting the smaller (more negative) sum.

Updating the Result

After adjusting high and low, the algorithm updates result with the greatest absolute value observed so far. Both the current maximum and minimum sums are considered because the absolute value of a large negative sum can exceed that of a positive sum.

    result = max(result, abs(high), abs(low))

Final Return

When the loop finishes, result contains the maximum absolute sub-array sum, which is returned to the caller.

return result

Edge Cases Handled

The algorithm gracefully handles several edge conditions without additional checks:

  • All Positive Numbers - The high variable continuously accumulates the sum of the entire array, while low remains non-negative. The absolute value of high dominates, yielding the sum of the whole array.
  • All Negative Numbers - high never grows beyond a single element because extending a negative sum would make it smaller. Meanwhile, low accumulates the most negative prefix, and its absolute value becomes the answer.
  • Mixed Signs with Zeroes - Zero values are treated like any other integer. When a zero appears, high may stay unchanged or restart, and low may similarly reset, ensuring that sub-arrays that cross zero are evaluated correctly.
  • Single-Element Input - The loop runs once, setting high and low to that element, and result becomes the absolute value of that element, which is the correct answer.
  • Empty List - Although the problem specification typically guarantees at least one element, the initialization of result to zero means that an empty list would return zero, a sensible default for the maximum absolute sum of no sub-arrays.

Performance Optimizations

The implementation achieves high efficiency through several deliberate choices:

  • Single Pass - By updating high, low, and result within the same loop, the algorithm processes the input in O(n) time, where n is the length of nums. No auxiliary data structures are allocated, keeping the memory footprint minimal.
  • In-Place Variable Reuse - The same variables are reused for each iteration, avoiding the creation of temporary lists or objects. This reduces garbage-collection pressure and improves cache locality.
  • Avoidance of Conditional Branches - The use of max and min functions encapsulates the conditional logic for extending or restarting sub-arrays. Modern interpreters often optimize these built-in functions, leading to faster execution compared with explicit if statements.
  • Absolute Value Computation Only When Needed - The algorithm computes abs(high) and abs(low) only once per iteration, directly feeding them into the max call that updates result. This avoids redundant absolute-value calculations.
  • Early Result Initialization - Starting result at zero ensures that the first iteration immediately captures the absolute value of the first element, eliminating the need for a separate initialization step after the loop.

Overall, the code delivers a concise, high-performance solution for determining the maximum absolute sub-array sum.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of building blocks in front of you. Some blocks have positive numbers written on them, which means they make your pile grow taller. Other blocks have negative numbers, which means they take pieces away from your pile. This code acts like a tiny robot that walks along the row of blocks one by one to find the best possible pile.

As the robot picks up each block, it keeps track of two special piles at the same time. One pile explores how high it can grow by adding up the numbers, and the other pile explores how far down it can go into negative territory. Every time the robot picks up a new block, it checks its two piles. It decides if it should start a brand new pile with just the block it is holding or if it should add that block to the pile it was already building.

After checking those piles, the robot looks at the very biggest number it has seen so far. It uses a trick to turn any negative pile into a positive one just to see how big the number is inside. It keeps updating its memory with the biggest size it finds throughout the whole walk. By the time the robot reaches the very last block, it has already figured out which group of blocks created the largest difference from zero.

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 = 8 | μ = 8.04 | σ = 0.96

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
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
28 links | 16 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 1 medium 2 hard
5 solutions   January 19, 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