Problem 1262

Abstract / Summary

Given an array of digits, find the largest sum of a subset of digits whose sum is divisible by three.

Note

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

Python 1262.py

class Solution:
    def maxSumDivThree(self, nums: List[int]) -> int:
        nums.sort()
        total = sum(nums)

        if total % 3 == 0:
            return total

        best = 0
        for i in range(len(nums)):
            if (total - nums[i]) % 3 == 0:
                best = total - nums[i]
                break

        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                both = nums[i] + nums[j]
                if total - both < best:
                    break
                if (total - both) % 3 == 0:
                    best = total - both
                    break

        return best
24 lines | 668 bytes | submitted August 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
  • Sorting
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 computes the maximum possible sum of a subset of integers such that the sum is divisible by three. It first evaluates the total sum of the input list, then checks whether the sum already satisfies the divisibility condition. If not, it attempts to discard the smallest one or two elements whose removal yields a sum divisible by three. The algorithm leverages sorting and early-exit logic to avoid unnecessary work, thereby keeping the execution focused on the most promising candidates.

Key Steps

Sorting the Input

The algorithm begins by arranging the numbers in non-decreasing order. This ordering is crucial for the subsequent removal logic because it guarantees that the first elements examined are the smallest possible candidates for exclusion, which in turn maximizes the remaining sum.

nums.sort()

Computing the Total Sum

A single pass over the sorted list produces the aggregate of all elements. This total serves as the baseline from which potential reductions are evaluated.

total = sum(nums)

Immediate Return When Already Divisible

If the total sum leaves no remainder when divided by three, the function can return the total immediately, as no removal is necessary.

if total % 3 == 0:
    return total

Attempting Single-Element Removal

When the total is not divisible by three, the code scans the list from the smallest element upward, checking whether subtracting that element yields a sum divisible by three. Because the list is sorted, the first successful removal also yields the largest possible remaining sum after a single deletion. The loop terminates as soon as a suitable element is found.

best = 0
for i in range(len(nums)):
    if (total - nums[i]) % 3 == 0:
        best = total - nums[i]
        break

Attempting Two-Element Removal

If a single removal does not produce a valid sum, the algorithm proceeds to consider pairs of elements. It iterates over all ordered pairs (i, j) with i < j. For each pair, it computes the combined value and checks whether subtracting this pair from the total yields a sum divisible by three. Two pruning conditions are applied:

  1. If the current candidate sum (total - both) is already less than the best sum found so far, the inner loop breaks because further pairs involving the same i will only increase the combined value (due to the sorted order) and thus produce even smaller remaining sums.
  2. Upon finding a valid pair, the best sum is updated and the inner loop breaks, because any later pair with the same i would involve larger numbers and therefore lead to a smaller remaining sum.
for i in range(len(nums)):
    for j in range(i + 1, len(nums)):
        both = nums[i] + nums[j]
        if total - both < best:
            break
        if (total - both) % 3 == 0:
            best = total - both
            break

Returning the Result

After exploring both single-element and two-element removal possibilities, the function returns the best sum discovered. If no removal yields a divisible sum, best remains zero, which correctly reflects that no non-empty subset satisfies the condition.

return best

Edge Cases Handled

The code gracefully addresses several boundary conditions:

  • Empty Input - When the input list is empty, the total sum is zero, which is divisible by three, leading to an immediate return of zero.
  • All Elements Identical - Sorting does not alter the order, and the removal loops still correctly evaluate the smallest (identical) elements for potential exclusion.
  • Single-Element List - If the sole element is not divisible by three, the single-element removal loop will detect that removing it yields a sum of zero, which satisfies the divisibility requirement, and best becomes zero.
  • Large Numbers with Small Remainder - The early-exit condition after finding the first valid removal ensures that the algorithm does not waste time scanning the remainder of the list once the optimal minimal removal is identified.
  • No Valid Subset - When no combination of one or two elements can adjust the total to a multiple of three, the loops complete without updating best, and the function returns zero, indicating that the empty subset is the only viable answer.

Performance Optimizations

The implementation incorporates several techniques that reduce the amount of work performed:

  • Single Sort Operation - By sorting the list once at the start, the algorithm avoids repeated ordering work and gains the ability to make assumptions about element magnitude during later scans.
  • Early Termination in Single-Element Loop - The break statement exits the loop as soon as a suitable element is found, preventing unnecessary checks of larger elements that would only decrease the remaining sum.
  • Pruning in Two-Element Loop - The condition if total - both < best: break leverages the sorted order to stop the inner loop early when further pairs cannot improve the current best result. This dramatically cuts down the number of pair evaluations, especially for longer lists.
  • Immediate Return on Divisible Total - The check for total % 3 == 0 eliminates all subsequent processing when the input already satisfies the requirement, saving both time and memory.

These optimizations collectively ensure that the algorithm focuses on the minimal set of candidates needed to achieve the maximal divisible sum, while avoiding exhaustive enumeration of all possible subsets.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of numbered blocks and you want to put as many of them together as possible to build a tower. The special rule for this tower is that the sum of all the numbers on the blocks must be able to be shared equally by three friends without any blocks left over.

First, the code lines up all the blocks from the smallest number to the biggest number so they are easy to look at. Then, it adds up all the numbers on every block to see if the total is already a friendly number that three people can share. If it is, the job is done.

If the total does not work, the code starts looking for the best way to fix the pile. It tries taking away just one block to see if the remaining pile can be shared by three friends. It keeps track of the biggest sum it finds that works with the rule.

After that, it tries taking away two blocks at a time to see if that makes a new, better total that fits the rule. It checks many pairs of blocks until it finds the best possible sum that keeps the rule happy. Once it has searched through the blocks, it holds onto the biggest number it found that everyone can share equally.

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 = 4 | μ = 4.96 | σ = 1.57

Complexity Analysis

Time: polynomial
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++ Java
leetcode.ca C++ Python Java Go TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
MacJim C++
suxrobGM C#
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
suxrobGM C#
wisdompeak C++
withaarzoo C++
26 links | 15 authors | 7 languages

Videos

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

Solved On The Same Day

20 solutions   August 14, 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