Skip to content

fix(dynamic-programming): preserve integer subarray sums - #15808

Open
lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/max-subarray-integer-precision
Open

lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/max-subarray-integer-precision

Conversation

@lanqing431

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Initializing the running sum to 0.0 coerces the first addition to float. With empty subarrays allowed this loses integer precision above 2**53; an integer larger than float range can raise OverflowError with either setting.

Initialize the accumulator to integer zero. Python then retains exact integer arithmetic for integer inputs and still promotes to float naturally when a float input is used. The algorithm and original doctests otherwise stay unchanged.

Reproduction / verification

from dynamic_programming.max_subarray_sum import max_subarray_sum

assert max_subarray_sum([2**53, 1], True) == 2**53 + 1
assert max_subarray_sum([10**400]) == 10**400
assert max_subarray_sum([-10**400, 10**400 + 1], True) == 10**400 + 1

Validated on Windows with CPython 3.15.2:

  • python -m doctest -v dynamic_programming/max_subarray_sum.py
  • python -m pytest dynamic_programming/max_subarray_sum.py --doctest-modules -q
  • python -m ruff check dynamic_programming/max_subarray_sum.py (Ruff 0.17.3)
  • python -m ruff format --check dynamic_programming/max_subarray_sum.py
  • Independent local regression checks: 1,570 checks against brute-force contiguous-subarray sums, with both allow_empty_subarrays settings, empty inputs, mixed signs, integers around 2**53, and 400-digit integers.

The regression harness found 201 failing cases on the unchanged upstream file and none after the fix (1570 checks). It is kept outside this source-only diff to follow the repository's instruction not to change implementation and doctests together. The original doctests remain unchanged. The complete repository suite and free-threaded CI were not run locally.

Checklist

  • I have read CONTRIBUTING.md and AGENTS.md.
  • This PR only changes one algorithm file.
  • Existing doctests pass and are unchanged.
  • The modified file passes Ruff lint and formatting checks.
  • CI checks have completed. (Not run until this PR is opened.)

AI assistance: OpenAI Codex assisted with source analysis, implementation, reproductions, local verification, and drafting this description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant