- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathmax_non_adjacent_sum.py
34 lines (27 loc) · 879 Bytes
/
max_non_adjacent_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ importannotations
defmaximum_non_adjacent_sum(nums: list[int]) ->int:
"""
Find the maximum non-adjacent sum of the integers in the nums input list
>>> maximum_non_adjacent_sum([1, 2, 3])
4
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
18
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
0
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
500
"""
ifnotnums:
return0
max_including=nums[0]
max_excluding=0
fornuminnums[1:]:
max_including, max_excluding= (
max_excluding+num,
max(max_including, max_excluding),
)
returnmax(max_excluding, max_including)
if__name__=="__main__":
importdoctest
doctest.testmod()