Skip to content

Commit 23484ef

Browse files
ruppysuppycclauss
andauthored
Added maximum non-adjacent sum (TheAlgorithms#2130)
* Added maximum non-adjacent sum * Bugfix: flake8 test * Implemented changes (broke tuple unpacking into 2 lines due to flake8 tests) * Implemented changes v2.0 * Update max_non_adjacent_sum.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent d7a75da commit 23484ef

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Video Explaination: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
2+
3+
from typing import List
4+
5+
6+
def maximum_non_adjacent_sum(nums: List[int]) -> int:
7+
'''
8+
Find the maximum non-adjacent sum of the integers in the nums input list
9+
10+
>>> print(maximum_non_adjacent_sum([1, 2, 3]))
11+
4
12+
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
13+
18
14+
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
15+
0
16+
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
17+
500
18+
'''
19+
if not nums:
20+
return 0
21+
max_including = nums[0]
22+
max_excluding = 0
23+
for num in nums[1:]:
24+
max_including, max_excluding = (
25+
max_excluding + num, max(max_including, max_excluding)
26+
)
27+
return max(max_excluding, max_including)
28+
29+
30+
if __name__ == "__main__":
31+
import doctest
32+
33+
doctest.testmod()

0 commit comments

Comments
 (0)