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.
Solution: we start from the last element and we try to see if that element belongs to the max subset group. There can be 4 scenarios:
* element belongs
* adjancent elements belongs instead
* element belongs with non-adjacent element
* non-adjacebnt elemnt belongs instead
* none belong, but that can be taken care of by making it recursively check what's best for the next step.
Here's the code:
# n <= 10^5sys.setrecursionlimit(100000)# Complete the maxSubsetSum function below.defmaxSubsetSum(arr):# for memoizationcache={}# subfunction for finding the right pathdefmax_subarr(position):ifpositionincache:returncache[position]result=0ifposition<0:returnresultelse:# choose the maximum between:# self, self + (non-adjacent next), adjacent next, non-adjacent nextresult=max(arr[position],arr[position]+max_subarr(position-2),max_subarr(position-1),max_subarr(position-2))# print("position %s result %s" % (position, result))# cache for memoizationcache[position]=resultreturnresultmaxSubSum=max_subarr(len(arr)-1)returnmaxSubSum
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 →
Solution: we start from the last element and we try to see if that element belongs to the max subset group. There can be 4 scenarios: * element belongs * adjancent elements belongs instead * element belongs with non-adjacent element * non-adjacebnt elemnt belongs instead * none belong, but that can be taken care of by making it recursively check what's best for the next step. Here's the code: