Python/dynamic_programming/max_non_adjacent_sum.py
Tianyi Zheng cc10b20beb
Remove some print statements within algorithmic functions (#7499)
* Remove commented-out print statements in algorithmic functions

* Encapsulate non-algorithmic code in __main__

* Remove unused print_matrix function

* Remove print statement in __init__

* Remove print statement from doctest

* Encapsulate non-algorithmic code in __main__

* Modify algorithm to return instead of print

* Encapsulate non-algorithmic code in __main__

* Refactor data_safety_checker to return instead of print

* updating DIRECTORY.md

* updating DIRECTORY.md

* Apply suggestions from code review

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-10-22 13:33:51 +02:00

35 lines
879 B
Python

# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ import annotations
def maximum_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
"""
if not nums:
return 0
max_including = nums[0]
max_excluding = 0
for num in nums[1:]:
max_including, max_excluding = (
max_excluding + num,
max(max_including, max_excluding),
)
return max(max_excluding, max_including)
if __name__ == "__main__":
import doctest
doctest.testmod()