Skip to content
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

Added #9 largest-non-adjacent-sum #1

Closed
wants to merge 3 commits into from

Conversation

NandanSatheesh
Copy link

largest-non-adjacent-sum was solved using Dynamic Programming approach.


DP[0] = array[0]
DP[1] = max(array[0] , array[1])

Choose a reason for hiding this comment

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

What happens when len(array)==1 ?

Choose a reason for hiding this comment

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

and also it fails when len(array)==0.

def maximumNonAdjacentSum(array):

DP = [0]*len(array)

Choose a reason for hiding this comment

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

space is O(n). It is not a constant space. If you look closely on the algorithm, you are using only three at any instance, DP_i, DP_i_1, DP_i_2. You can rewrite the alogithm to do that

for i in range(2,len(array)):

DP[i] = max3( array[i] , array[i] + DP[i-2] , DP[i-1])
print(DP)

Choose a reason for hiding this comment

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

as pointed out above rewrite this line to use constant space

@amritansh24 amritansh24 mentioned this pull request Apr 29, 2019
@NandanSatheesh
Copy link
Author

Will make the necessary changes and raise a new PR again. Thanks for the feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants