FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix: handle empty array in maximumNonAdjacentSum by shaked-shlomo · Pull Request #1905 · TheAlgorithms/JavaScript · GitHub

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .js  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
2 changes: 1 addition & 1 deletion Dynamic-Programming/MaxNonAdjacentSum.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ function maximumNonAdjacentSum(nums) {
* :return: The maximum non-adjacent sum
*/

if (nums.length < 0) return 0
if (nums.length === 0) return 0

let maxIncluding = nums[0]
let maxExcluding = 0
Expand Down
21 changes: 21 additions & 0 deletions Dynamic-Programming/tests/MaxNonAdjacentSum.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { maximumNonAdjacentSum } from '../MaxNonAdjacentSum'

describe('maximumNonAdjacentSum', () => {
it('should return 0 for an empty array', () => {
expect(maximumNonAdjacentSum([])).toBe(0)
})

it('should return the single element for a one-element array', () => {
expect(maximumNonAdjacentSum([5])).toBe(5)
})

it('should compute the maximum non-adjacent sum', () => {
expect(maximumNonAdjacentSum([1, 2, 3])).toBe(4)
expect(maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6])).toBe(18)
expect(maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6])).toBe(500)
})

it('should return 0 when all elements are negative', () => {
expect(maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6])).toBe(0)
})
})
Loading

Back | FazBrowse Home | New Git URL