Skip to content

Commit ad30e27

Browse files
Shaked ShlomoShaked Shlomo
authored andcommitted
fix: handle empty array in maximumNonAdjacentSum
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.
1 parent 5c39e87 commit ad30e27

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

Dynamic-Programming/MaxNonAdjacentSum.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ function maximumNonAdjacentSum(nums) {
55
* :return: The maximum non-adjacent sum
66
*/
77

8-
if (nums.length < 0) return 0
8+
if (nums.length === 0) return 0
99

1010
let maxIncluding = nums[0]
1111
let maxExcluding = 0
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { maximumNonAdjacentSum } from '../MaxNonAdjacentSum'
2+
3+
describe('maximumNonAdjacentSum', () => {
4+
it('should return 0 for an empty array', () => {
5+
expect(maximumNonAdjacentSum([])).toBe(0)
6+
})
7+
8+
it('should return the single element for a one-element array', () => {
9+
expect(maximumNonAdjacentSum([5])).toBe(5)
10+
})
11+
12+
it('should compute the maximum non-adjacent sum', () => {
13+
expect(maximumNonAdjacentSum([1, 2, 3])).toBe(4)
14+
expect(maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6])).toBe(18)
15+
expect(maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6])).toBe(500)
16+
})
17+
18+
it('should return 0 when all elements are negative', () => {
19+
expect(maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6])).toBe(0)
20+
})
21+
})

0 commit comments

Comments
 (0)