Skip to content

fix: handle empty array in maximumNonAdjacentSum - #1905

Open
shaked-shlomo wants to merge 1 commit into
TheAlgorithms:masterfrom
shaked-shlomo:fix/max-nonadjacent-empty-input
Open

fix: handle empty array in maximumNonAdjacentSum#1905
shaked-shlomo wants to merge 1 commit into
TheAlgorithms:masterfrom
shaked-shlomo:fix/max-nonadjacent-empty-input

Conversation

@shaked-shlomo

Copy link
Copy Markdown

Bug

Dynamic-Programming/MaxNonAdjacentSum.js guards the empty case with:

if(nums.length<0)return0

length is never negative, so this is dead code. For an empty array the function falls through, sets maxIncluding = nums[0] (undefined), skips the loop, and returns Math.max(0, undefined)NaN instead of 0.

maximumNonAdjacentSum([])// NaN (should be 0)

Fix

Use nums.length === 0, matching the clearly-intended behavior. Added a test file (the module had none) covering the empty array, a single element, the documented examples, and an all-negative input.

The empty-input guard was 'if (nums.length < 0) return 0', but length is
never negative, so it was dead code. For [] the function then read
nums[0] (undefined) and returned Math.max(0, undefined) === NaN instead
of 0. Change the guard to 'nums.length === 0' and add a test file.
@codecov-commenter

codecov-commenter commented Jun 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.06%. Comparing base (5c39e87) to head (ad30e27).

Additional details and impacted files
@@ Coverage Diff @@## master #1905 +/- ##
==========================================
+ Coverage 85.91% 86.06% +0.14% 
==========================================
Files 379 379 Lines 19778 19778 Branches 3016 3020 +4 ==========================================
+ Hits 16993 17022 +29 + Misses 2785 2756 -29 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for freeto 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.

2 participants

@shaked-shlomo@codecov-commenter