File: maximum-product-of-three-numbers/solution.py

Date: 2026-06-06

Time: 17:42

maximum-product-of-three-numbers/solution.py

Purpose

This file solves LeetCode 628: Maximum Product of Three Numbers. It owns the solution implementation and its test suite in a single module — the standard layout across this repo.

Key Components

maximumProduct(nums: List[int]) -> int — The sole public function. Contract: given a list of at least 3 integers (positive, negative, or zero), return the largest product achievable by choosing exactly three elements.

TestMaximumProduct — 10 unit tests covering the meaningful equivalence classes: all positive, all negative, mixed signs, zeros, duplicates, and the critical case where two large negatives times a positive beats three positives.

Patterns

Sort-then-inspect. Rather than tracking running extremes, the solution sorts in O(n log n) and reads fixed positions. This trades optimal O(n) time for simpler code — a common choice in this repo's easy-level solutions.

Single-file solution+test. Matches the repo convention: solution.py contains both implementation and unittest tests, runnable via python -m unittest or python solution.py.

Dependencies

Imports: typing.List (type annotation), unittest (test framework). No project-internal dependencies.

Imported by: The "Imported By" list is misleading — those 400+ test files don't actually import this module. That list reflects a repo-wide cross-reference artifact, not real import edges. This file is self-contained.

Flow

1. Sort nums in-place (ascending).

2. Compute two candidate products:

3. Return the max of those two candidates.

The key insight: when the array contains large-magnitude negatives, multiplying two negatives yields a positive that, combined with the largest element, can exceed the product of the three largest. These are the only two candidates that can ever win — no other combination of three indices from a sorted array can produce a larger product.

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. Passing fewer than 3 elements raises an IndexError from the list access — no custom error handling.