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.
Simple Python Solution - fully commented and easy to understand, also takes into account 1 element case (test cases don't cover this):
defmaxSubsetSum(arr):length=len(arr)# Initialize a solution array (dp) to store the solution# to the problem for numbers from index 0 to index i# at dp[i]dp=[0]*length# Initialize dp[0] as the first element of the array (or 0) if it is negativedp[0]=max(arr[0],0)# Stop and return dp[0] if the length of the array is 1iflength==1:returndp[0]# Initialize dp[1] as the max of the first element, second element (or 0)dp[1]=max(dp[0],arr[1])# Set dp[1] to the maximum of the previous solution or 2 solutions back + the# current value in the array (disallowing adjacent elements to be added to the set)foriinrange(2,length):dp[i]=max(dp[i-2]+arr[i],dp[i-1])# Returning the solution for the whole array (as the last element in the dp array)returndp[-1]
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 →
Simple Python Solution - fully commented and easy to understand, also takes into account 1 element case (test cases don't cover this):