Max Array Sum

  • + 1 comment

    Simple Python Solution - fully commented and easy to understand, also takes into account 1 element case (test cases don't cover this):

    def maxSubsetSum(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 negative
        dp[0] = max(arr[0], 0)
        
        # Stop and return dp[0] if the length of the array is 1
        if length == 1:
            return dp[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)
        for i in range(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)
        return dp[-1]