2020-07-06 03:18:18 +00:00
|
|
|
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
|
2020-06-17 15:09:29 +00:00
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
from __future__ import annotations
|
2020-06-17 15:09:29 +00:00
|
|
|
|
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
def maximum_non_adjacent_sum(nums: list[int]) -> int:
|
2020-06-22 12:16:12 +00:00
|
|
|
"""
|
2020-06-17 15:09:29 +00:00
|
|
|
Find the maximum non-adjacent sum of the integers in the nums input list
|
|
|
|
|
|
|
|
>>> print(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
|
2020-06-22 12:16:12 +00:00
|
|
|
"""
|
2020-06-17 15:09:29 +00:00
|
|
|
if not nums:
|
|
|
|
return 0
|
|
|
|
max_including = nums[0]
|
|
|
|
max_excluding = 0
|
|
|
|
for num in nums[1:]:
|
|
|
|
max_including, max_excluding = (
|
2020-06-22 12:16:12 +00:00
|
|
|
max_excluding + num,
|
|
|
|
max(max_including, max_excluding),
|
2020-06-17 15:09:29 +00:00
|
|
|
)
|
|
|
|
return max(max_excluding, max_including)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|