File: maximum-product-of-two-elements-in-an-array/solution.py

Date: 2026-06-06

Time: 17:42

Purpose

This file is a self-contained solution to LeetCode 1464: Maximum Product of Two Elements in an Array. It owns the algorithm implementation and its unit tests. In the broader leetcode-implementations repo, it follows the standard per-problem directory structure (solution.py + test_solution.py + optional plan.md/review.md).

Key Components

max_product(nums: List[int]) -> int

The sole algorithm function. Given an array of non-negative integers with at least two elements, it returns the maximum value of (nums[i] - 1) * (nums[j] - 1) where i != j.

The implementation uses a single-pass two-max tracker rather than sorting:


max1 = max2 = 0
for n in nums:
    if n >= max1:
        max2 = max1
        max1 = n
    elif n > max2:
        max2 = n

max1 holds the largest value seen, max2 holds the second largest. The final result is (max1 - 1) * (max2 - 1).

TestMaxProduct

Eight test cases covering examples from the problem statement, edge cases (all ones, identical values, max constraint values), and ordering variants (ascending, descending input).

Patterns

Dependencies

Imports: unittest (stdlib) and typing.List (type annotation only — no runtime dependency).

Imported by: The test_solution.py file in this same directory imports from it. The massive "Imported By" list in the prompt is misleading — those are *other problems'* test files that happen to share the same import pattern (from solution import ...), not actual cross-problem dependencies.

Flow

1. Initialize max1 and max2 to 0 (safe because the problem guarantees nums[i] >= 1).

2. Single pass through nums:

3. Return (max1 - 1) * (max2 - 1).

Invariants

Error Handling

None. The function trusts its caller to provide valid input per the LeetCode constraints (2 <= len(nums) <= 500, 1 <= nums[i] <= 10^3). No validation, no exceptions. This is appropriate for a competitive-programming solution.

Topics to Explore

Beliefs