From 23484efdad9afc33259adb5753fe2d378e61c37a Mon Sep 17 00:00:00 2001 From: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> Date: Wed, 17 Jun 2020 20:39:29 +0530 Subject: [PATCH] Added maximum non-adjacent sum (#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 --- dynamic_programming/max_non_adjacent_sum.py | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 dynamic_programming/max_non_adjacent_sum.py diff --git a/dynamic_programming/max_non_adjacent_sum.py b/dynamic_programming/max_non_adjacent_sum.py new file mode 100644 index 000000000000..1d771f21f3fb --- /dev/null +++ b/dynamic_programming/max_non_adjacent_sum.py @@ -0,0 +1,33 @@ +# Video Explaination: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo + +from typing import List + + +def maximum_non_adjacent_sum(nums: List[int]) -> int: + ''' + 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 + ''' + 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()