Maximise array sum after taking non | Python3 implementation of the approach ; To store the states of dp ; To check if a given state has been solved ; To store the prefix - sum ; Function to fill the prefix_sum [ ] with the prefix sum of the given array ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code ; Finding prefix - sum ; Finding the maximum possible sum
maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE v = [ 0 ] * maxLen ; NEW_LINE prefix_sum = [ 0 ] * maxLen ; NEW_LINE def findPrefixSum ( arr , n ) : NEW_LINE INDENT prefix_sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ i ] = arr [ i ] + prefix_sum [ i - 1 ] ; NEW_LINE DEDENT DEDENT def maxSum ( arr , i , n , k ) : NEW_LINE INDENT if ( i + k > n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT v [ i ] = 1 ; NEW_LINE if ( i == 0 ) : NEW_LINE INDENT x = prefix_sum [ k - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = prefix_sum [ i + k - 1 ] - prefix_sum [ i - 1 ] ; NEW_LINE DEDENT dp [ i ] = max ( maxSum ( arr , i + 1 , n , k ) , x + maxSum ( arr , i + k + 1 , n , k ) ) ; NEW_LINE return dp [ i ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 7 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 1 ; NEW_LINE findPrefixSum ( arr , n ) ; NEW_LINE print ( maxSum ( arr , 0 , n , k ) ) ; NEW_LINE DEDENT