Skip to content

Added maximum non-adjacent sum #2130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 17, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions dynamic_programming/max_non_adjacent_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from typing import List


def max_non_adj_sum(nums: List[int]) -> int:
'''
Function to find the maximum non-adjacent sum of the elements in the input list

Parameters
----------
nums : List[int]
List of integers for the maximum non-adjacent sum computation

Returns
-------
int
maximum non-adjacent sum
Copy link
Member

@cclauss cclauss Jun 17, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Function to find the maximum non-adjacent sum of the elements in the input list
Parameters
----------
nums : List[int]
List of integers for the maximum non-adjacent sum computation
Returns
-------
int
maximum non-adjacent sum
Find the maximum non-adjacent sum of the integers in the nums input list

Type hints and careful naming of functions and variables makes a lot of comments unnecessary boilerplate.

  1. def tells us that this is a function.
  2. The self-documenting function name tells us what this function does.
  3. The type hints already tell us that nums is a list of integers.
  4. The type hint on the return value tells us that we will return an int.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking into it


Examples
--------
These are written in doctest format, and should illustrate how to use the function

>>> print(max_non_adj_sum([1, 2, 3]))
4

>>> max_non_adj_sum([1, 5, 3, 7, 2, 2, 6])
18

>>> max_non_adj_sum([-1, -5, -3, -7, -2, -2, -6])
0

>>> max_non_adj_sum([499, 500, -3, -7, -2, -2, -6])
500
'''

if (len(nums) == 0):
return 0

max_including = nums[0]
max_excluding = 0

for num in nums[1:]:
temp = max_including
max_including = max_excluding + num
max_excluding = max(temp, max_excluding)

return max(max_excluding, max_including)


if __name__ == "__main__":
import doctest

doctest.testmod()