We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def max_sum_non_adjacent(arr):
if not arr:
return 0
if len(arr) == 1:
return arr[0]
# Initialize prev2 (max sum until i-2) and prev1 (max sum until i-1)
prev2 = 0
prev1 = 0
# Traverse through the array
for num in arr:
current = max(prev1, num + prev2)
prev2 = prev1
prev1 = current
return prev1
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Max Array Sum
You are viewing a single comment's thread. Return to all comments →
def max_sum_non_adjacent(arr): if not arr: return 0 if len(arr) == 1: return arr[0]